事實證明,
題目給的空間,留著不用不但是一種浪費,而且很有可能是自殺行為!這一題就是因為我把數組開小了,它無情的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
小鼠標 閱讀(1197)
評論(0) 編輯 收藏 引用 所屬分類:
暑期培訓周賽