九度OJ 1010 A+B

来源:互联网 发布:itools不能下载软件 编辑:程序博客网 时间:2024/05/16 08:20

题目链接:http://ac.jobdu.com/problem.php?pid=1010


题目分析:

先写一个函数将输入的数字单词转化为对应的数字,在计算值的时候调用该函数。

主要的算法在于对于输入字符串的逻辑判断,即:输入几个数字单词,什么时候打印值。

我的设计思想是:首先读入一个数字单词,然后读入下一个输入的字符串(中间判断空格在这里就不说了),判断先一个字符串是加号还是数字单词。是加号的话,继续输入字符串,那么这个必然是数字单词,再继续输入,判断是等于号还是数字单词,这里两种情况结果就都可以输出了;第一个数字单词之后如果依然是数字单词的话,那么继续输入,必然是加号,在进行上面加号之后的判断,依然有两种情况的输出。最后再判别一下都是0的退出情况。


源代码:

#include <iostream>#include <string>#include <stdio.h>using namespace std;int toInteger(string A){if(A=="one")return 1;else if(A=="two")return 2;else if(A=="three")return 3;else if(A=="four")return 4;else if(A=="five")return 5;else if(A=="six")return 6;else if(A=="seven")return 7;else if(A=="eight")return 8;else if(A=="nine")return 9;else if(A=="zero")return 0;elsereturn -1;}int main(){string A1,A2,B1,B2,t1,t2;int num1,num2,sum;while (cin>>A1){num1 = toInteger(A1);char c;c = getchar();if (c == ' '){cin>>t1;if (t1[0] == '+')//判断第二个输入字符串为+{c = getchar();if (c == ' '){cin >> B1;//输入第三个字符串数字单词num2 = toInteger(B1);c = getchar();if (c == ' '){cin>>t2;if (t2[0] == '=')//判断最后输入的字符串为={if (num1 == 0 && num2 == 0){break;}else{cout<<num1 + num2<<endl;}}else//不是=,为数字单词{num2 = num2 * 10 + toInteger(t2);cout<<num1 + num2<<endl;}}}}else//第一个数字单词之后不为+,则为另一个数字单词{num1 = num1 * 10 + toInteger(t1);c = getchar();if (c == ' '){cin >> t1;//输入加号c = getchar();if (c == ' '){cin >> B1;//输入第三个字符串数字单词num2 = toInteger(B1);c = getchar();if (c == ' '){cin>>t2;if (t2[0] == '=')//判断最后输入的字符串为={cout<<num1 + num2<<endl;}else//不是=,为数字单词{num2 = num2 * 10 + toInteger(t2);cout<<num1 + num2<<endl;}}}}}}}return 0;}


原创粉丝点击