Inglish-Number Translator(含map做法)

map做法:map应用:Inglish-Number Translator(map做法).
In this problem, you will be given one or more integers in English. Your task is to translate these numbers into their integer representation. The numbers can range from negative 999,999,999 to positive 999,999,999. The following is an exhaustive list of English words that your program must account for:
negative, zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety, hundred, thousand, million
Input
The input consists of several instances. Notes on input:
Negative numbers will be preceded by the word negative.
The word “hundred” is not used when “thousand” could be. For example, 1500 is written “one thousand five hundred”, not “fifteen hundred”.

The input is terminated by an empty line.
Output
The answers are expected to be on separate lines with a newline after each.
Sample Input
six
negative seven hundred twenty nine
one million one hundred one
eight hundred fourteen thousand twenty two

Sample Output
6
-729
1000101
814022

#include<stdio.h>
#include<string.h>
char s[100][100]={
    
    "negative","zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","hundred","thousand","million"};//二维字符串存
int s1[100]={
    
    -1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,30,40,50,60,70,80,90,100,1000,1000000};//对应的二维字符串的数
int f(char a[])//函数返回对应的值
{
    
    
	int i,j=1;
	for(i=0;;i++)
	{
    
    
		if(strcmp(a,s[i])==0)
		return s1[i];
	}
}
int main()
{
    
    
	int i,j,k,l;
	char a[10100];char b[100][100]; //分开存
	while(gets(a))
	{
    
    
		memset(b,'\0',sizeof(b));//初始化字符串b,不然会错
		l=strlen(a);int ss=0,sum=0,ff=1;//ff判断正负
		if(l==0)
		break;//结束标志
		for(i=0,j=0,k=0;i<l;i++)
		{
    
    
			if(a[i]==' ')//把字符串a以空格为基础分割到二位字符串b里面去
			j++,k=0;//注意初始化k,j代表行数
			else
			b[j][k++]=a[i];
		}
		for(i=0;i<=j;i++)
		{
    
    
			if(f(b[i])<100&&f(b[i])!=-1)
			{
    
    
				ss+=f(b[i]);//模拟法小于100直接加
			}
			else if(f(b[i])==-1)
			ff=-1;//判断+-
			else
			{
    
    
				int t=f(b[i]);
				if(t==100)//模拟
				ss*=t;
				else if(t==1000)
				sum+=ss*1000,ss=0;
				else
				sum+=ss*t,ss=0;
			}
		}
		printf("%d\n",(sum+ss)*ff);//输出
	}
 } 

猜你喜欢

转载自blog.csdn.net/m0_46381590/article/details/112939130