数字的口头表达
很多时候一个数字需要转为口语,比如说5就是five,19是nineteen,39是thirty nine 等等如此。
其实这类题目是一种考察递归的方法,至少我觉得递归很简单。基本思想就是给一个数字,刨掉百位就是十位数如何表达,再把他们拼起来组成数组。理论上可以实现无穷正整数的英语表达。唯一需要考虑的就是and问题。比如160是one hundred and sixty。百位和十位之间一定有and,除非十位和个位都是0.而千位和百位没有and,但是如果百位是0且个位或十位不同时为0,则又要加and了。所以问题很复杂。
这里只考虑到10万以内的英语表达,其实后面一样,不断加million,billion用strcat贴起来即可。
那么下面上代码。
#include <stdio.h>
#include <string.h> //主要是为了strcpy和strcat
char *num[20] = { " ", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN","EIGHT",
"NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN",
"SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN" }; //制作好数字中文
char *num2[8] = { "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" };
int int2call(int amount, char *buffer) //这个函数是返回buffer——存放英文的字符数组长度的,便于后面打印,amount是数字
{
int i,j,k;
char temp[50],temp2[50];
if(amount <= 19) //1~19
{
strcpy(buffer,num[amount]);
}
else if(amount >=20 && amount <= 99)//20~99
{
i = amount/10-2;
j = amount%10;
strcpy(buffer,num2[i]);
if(j != 0)
{
strcat(buffer," ");
strcat(buffer,num[j]);
}
}
else if(amount >= 100 && amount <=999)//100~999
{
i = amount/100;
j = amount -i*100;
strcpy(buffer,num[i]);
strcat(buffer," ");
strcat(buffer,"HUNDRED");
if(j >= 1) //如果是100,200,300这种就没有后续了
{
strcat(buffer," AND ");//加and
int2call(j,temp);
strcat(buffer,temp);
}
}
else if(amount >= 1000 && amount <= 9999) //1000~9999
{
i = amount/1000;
j = amount - i*1000;
strcpy(buffer,num[i]);
strcat(buffer," ");
strcat(buffer,"THOUSAND");
if(j<=99 && j>=1) //特殊情况百位为0,加AND
{
strcat(buffer," AND");
}
if(j >= 1) //如果后面都是0就结束,不为0则递归
{
strcat(buffer," ");
int2call(j,temp);
strcat(buffer,temp);
}
}
else if(amount >= 10000 && amount <= 99999)//1000~99999
{
i = amount/1000;
j = amount - i*1000;
int2call(i,temp);
strcpy(buffer,temp);
strcat(buffer," ");
strcat(buffer,"THOUSAND");
if(j<=99 && j>=1) //和上面一样,不说了
{
strcat(buffer," AND");
}
if(j>=1) //递归
{
strcat(buffer," ");
int2call(j,temp2);
strcat(buffer,temp2);
}
}
return strlen(buffer);
}
int main()
{
int amout = 0;
int i,j,k;
int length = 0;
char buffer[100];
scanf("%d",&amout);
if(amout>99999 || amout <= 0)
{
printf("ERROR\n");
return 0;
}
length = int2call(amout,buffer);
for(i = 0;i<length;i++)
{
printf("%c",buffer[i]);
}
return 0;
}
最后输入数字看看:
2099
TWO THOUSAND AND NINETY NINE
29381
TWENTY NINE THOUSAND THREE HUNDRED AND EIGHTY ONE
432
FOUR HUNDRED AND THIRTY TWO
1098
ONE THOUSAND AND NINETY EIGHT
嗯,没毛病。