HDU-1228,A + B(字符串处理)

Problem Description:

读入两个小于100的正整数A和B,计算A+B.
需要注意的是:A和B的每一位数字由对应的英文单词给出. 

Input: 

测试输入包含若干测试用例,每个测试用例占一行,格式为"A + B =",相邻两字符串有一个空格间隔.当A和B同时为0时输入结束,相应的结果不要输出.  

Output: 

对每个测试用例输出1行,即A+B的值. 

Sample Input: 

one + two =

three four + five six =

zero seven + eight nine =

zero + zero = 

Sample Output: 

3

90

96 

解题思路:

 这道题我们可以利用样例中的“+”和“=”来作为分隔符,用scanf去读入,因为这样就可以被中间的空格给中断,然后用strcmp进行比较就可以了,比较成功的将其转换成数字进行计算即可。具体的我们看代码

 程序代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char a[10][6]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int ans(char ch[])
{
	for(int i=0;i<10;i++)
		if(strcmp(ch,a[i])==0)
			return i;
}
int main()
{
	char b[50],c[50];
	while(1)
	{
		int x=0,y=0;
		while(scanf("%s",b)&&strcmp(b,"+")!=0)
			x=x*10+ans(b);
		while(scanf("%s",c)&&strcmp(c,"=")!=0)
			y=y*10+ans(c);
		if(x==0&&y==0)
			return 0;
		else
			printf("%d\n",x+y);
	}
	return 0;
}
发布了260 篇原创文章 · 获赞 267 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43823808/article/details/103956870
今日推荐