主题:谁能编这个c语言——“one+two=3”?
wm5588
[专家分:0] 发布于 2011-04-15 19:22:00
题目:one + two = 3
要求:
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
回复列表 (共1个回复)
沙发
fragileeye [专家分:1990] 发布于 2011-04-15 22:49:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
#define M 10
#define MAXSTRING 30
typedef struct LinkList
{
char words[M];
struct LinkList *next;
}*WordsList;
const char *s[N] = {
"zero", "one", "two", "three", "four","five",
"six", "seven", "eight", "nine"
};
int check_loc(char *);
int words_plus(char *, WordsList );
void print_list(WordsList );
int main()
{
char input[MAXSTRING], check;
WordsList wordslist, list_p, list_q;
int index, ct, result;
result = 0;
do{
puts("输入等式(输入zero + zero = 结束)");
list_p = wordslist = (WordsList )malloc(sizeof(struct LinkList));
list_q = (WordsList )malloc(sizeof(struct LinkList)); //构造链表
fgets(input, MAXSTRING, stdin);
for(ct = index = 0; input[index] != '\0'; index++) //将字符装入链表一个节点中,遇到空格结束,即每个节点装一个单词
{
check = input[index];
if(check != ' ')
{
list_q->words[ct] = check;
ct++;
if(check == '=') //如果是‘=’,装完后直接跳出了
{
list_q->words[ct] = '\0';
list_p->next = list_q;
list_p = list_q;
break;
}
}
else
{
list_q->words[ct] = '\0'; //链表后移的操作
list_p->next = list_q;
list_p = list_q;
ct = 0;
list_q = (WordsList )malloc(sizeof(struct LinkList));
}
}
list_p->next = NULL;
print_list(wordslist); //打印表达式
result = words_plus(input, wordslist);
if(result != 0)
{
printf("%d\n", result);
}
free(wordslist);
}while(result != 0);
return 0;
}
int check_loc(char *p) //将单词转化为数字
{
int index;
for(index = 0; index < N; index++)
{
if(strcmp(p, s[index]) == 0)
{
return index;
}
}
}
void print_list(WordsList wordlist)
{
WordsList list_p = wordlist->next; //跳过 ‘+’
while(list_p != NULL)
{
printf("%s ", list_p->words);
list_p = list_p->next;
}
}
int words_plus(char *input, WordsList wordslist) //实现数字相加
{
int index, n1, n2;
WordsList list_p = wordslist->next;
n1 = n2 = 0;
while(strcmp(list_p->words, "+") != 0)
{
n1 = n1 * 10 + check_loc(list_p->words);
list_p = list_p->next;
}
list_p = list_p->next;
while(strcmp(list_p->words, "=") != 0)
{
n2 = n2 * 10 + check_loc(list_p->words);
list_p = list_p->next;
}
return (n1+n2);
}
//不知为什么贴代码贴不上,lz凑合着看吧,代码没规范写,没有精简、、没有容错(只能zero + zero =结束,不然出错。而且单词输入错误也没有提示以及重新输入!当然,lz想有更好的效果,自己写写吧)
算法就是这样吧。。
我来回复