事实证明,
题目给的空间,留着不用不但是一种浪费,而且很有可能是自杀行为!这一题就是因为我把数组开小了,它无情的SF啦~(>_<)~,我幼小的心灵再次受到创伤。
题意描述:
我们知道英语描述数字与汉语是不同的,题目要求给出英文描述的数字,输出实际的数字。
解题思路是,把所有关键字分成两类,一类是“数字”,另一类是“权重”,遇到数字就加上去,遇到权重就乘上去,最后输出结果就是了。不过这样还不行,因为这会导致权重累计相乘,比如前面有一个million,要乘1000 000,后面又有一个thousand,还要乘1000,这显然是不对的。解决办法是,遇到million或thousand后就再用一个变量从新计数,最后把所有用来计数的变量加起来就行了。
字符串处理,细节特别重要。
以下是本题代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN 5000
#define LENS 5000
#define LENSTR 5000
typedef struct
{
char *s;
int isn;//是数字
int isw;//是权重
int n;
int w;
}KeyWord;
KeyWord key[] = //多么坑爹的初始化啊
{
{"million", 0, 1, 0, 1000000},
{"thousand", 0, 1, 0, 1000},
{"hundred", 0, 1, 0, 100},
{"and", 0, 1, 0, 1},
{"zero", 1, 0, 0, 0},
{"one", 1, 0, 1, 0},
{"two",1 ,0, 2, 0},
{"three", 1, 0, 3, 0},
{"four", 1, 0, 4, 0},
{"five", 1, 0, 5, 0},
{"six", 1, 0, 6, 0},
{"seven", 1, 0, 7, 0},
{"eight", 1, 0, 8, 0},
{"nine", 1, 0, 9, 0},
{"ten", 1, 0, 10, 0},
{"eleven", 1, 0, 11, 0},
{"twelve", 1, 0, 12, 0},
{"thirteen", 1, 0, 13, 0},
{"fourteen", 1, 0, 14, 0},
{"fifteen", 1, 0, 15, 0},
{"sixteen", 1, 0, 16, 0},
{"seventeen", 1, 0, 17, 0},
{"eighteen", 1, 0, 18, 0},
{"nineteen", 1, 0, 19, 0},
{"twenty", 1, 0, 20, 0},
{"thirty", 1, 0, 30, 0},
{"forty", 1, 0, 40, 0},
{"fifty", 1, 0, 50, 0},
{"sixty", 1, 0, 60, 0},
{"seventy", 1, 0, 70, 0},
{"eighty", 1, 0, 80, 0},
{"ninety", 1, 0, 90, 0},
{"", 0, 0, 0, 0}
};
int Find(char s[])//在key[]中查找该关键字
{
int i = 0;
while(strcmp(key[i].s, "") != 0)
{
if(strcmp(s, key[i].s) == 0)
return i;
i++;
}
}
int mysScanf(char str[], char s[], int bg)//从字符串str[]读取单词,并返回该单词的结束位置
{
if(str[bg] == '\0')
{
s[bg] = '\0';
return -1;
}
int i, j;
i = bg - 1;
while(str[++i] == ' ');
j = 0;
for(; str[i] != ' ' && str[i] != '\0'; i++)
s[j++] = str[i];
s[j] = '\0';
return i;
}
int main()
{
int i, j;
int T;
int sum;
char str[LENSTR];
char s[LENS];
scanf("%d", &T);
getchar();
while(T--)
{
gets(str);
int t = 0;
int fd;
sum = 0;
int rs[3] = {0};
int k = 0;
while((t = mysScanf(str, s, t)) != -1)
{
fd = Find(s);
if(key[fd].isn == 1)
{
rs[k] += key[fd].n;
}
else if(key[fd].isw == 1)
{
rs[k] *= key[fd].w;
}
if(strcmp(s, "million") == 0 || strcmp(s, "thousand") == 0)
k++;
}
sum = rs[0] + rs[1] + rs[2];
printf("%d\n", sum);
}
//system("pause");
}
posted on 2012-08-12 09:18
小鼠标 阅读(1193)
评论(0) 编辑 收藏 引用 所属分类:
暑期培训周赛