用英文单词模拟数学计算
读入两个小于100的正整数A和B,计算A+B。需要注意的是:A和B的每一位数字由对应的英文单词给出。
具体的输入输出格式规定如下:
输入格式:测试输入包含若干测试用例,每个测试用例占一行,格式为“A+B=",相邻两字符串有一个空格间隔。当A和B同时为zero时输入结束,相应的结果不要输出。
输出格式:对每个测试用例输出1行,即A+B的值。
输入样例:
one+ two =
three four +five six=
zero seven +eight nine =
zero + zero =
输出样例:
three
nine zero
nine six
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE (200)
char *array[] = {"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"};
void procstr(char *string, int *left, int *right)
{
char words[50][MAXSIZE];
char c;
int i, num = 0, word = 0, j;
/*
*这部分的功能就是将字符串分解
* 输入为 one + two =
* 分解为:
* words[0] = "one"
* words[1] = "+"
* words[2] = "two"
* words[3] = "="
*/
for(i = 0; (c = string[i]) != '\0'; i++) {
if (c == ' ') {
if (word) {
strncpy(words[num-1], &string[i-word], word);
words[num-1][word] = '\0';
}
word = 0;
} else if (word == 0) {
word++;
num++;
} else {
word++;
}
}
if (word) {
strncpy(words[num-1], &string[i-word], word);
words[num-1][word] = '\0';
}
/*****************************************/
/*
* 这里的功能就是把
* + 左边的转换为整数放入 left 里面
* + 右边的转换为整数放入 right 里面
*/
*left = 0 , *right = 0;
int leftok = 0;
for(i = 0; i<num - 1; i++) {
if (strcmp(words[i], "+") == 0) {
leftok = 1;
} else {
for (j = 0; j < 10; j++) {
if (strcmp(words[i], array[j]) == 0) {
if (leftok == 1) {
*right = (*right) * 10 + j;
} else {
*left = (*left) * 10 + j;
}
}
}
}
}
}
/* 显示结果 */
void showRes(int res)
{
int stack[20], top = -1;
do {
stack[++top] = res % 10;
res /= 10;
} while (res != 0);
for (int i = top; i>=0; i--) {
if (i != 0) {
printf("%s ", array[stack[i]]);
} else {
printf("%s\n", array[stack[i]]);
}
}
}
int main()
{
char str[MAXSIZE] = {'\0'};
int left = 0, right = 0;int sum;
while(1) {
fgets(str, MAXSIZE - 1, stdin);
procstr(str, &left, &right);
if (left == 0 && right == 0) {
break;
} else {
showRes(left + right);
}
}
system("pause");
return 0;
}