数字翻译器及其实现
程序员文章站
2022-05-29 21:07:31
...
【问题描述】
输入一个正整数N(N最大是4位数),输出它的英文表达。
【样例】
输入:1
输出:one
又输入:12
输出:twelve
右输入:135
输出:one hundred thirty five
思路:1、首先19以内的数字,可以直接输出。。
2、20~~~99以内的数字,整十的整数可以直接输出。否则,除以10输出十位数字,与10取模输出个位数字。
3、100~~~999以内的数字,除以100输出百位数字,与100取模得到一个两位的数字,转到2
4、1000~~~9999以内的数字,除以1000输出千位数字,与1000取模得到一个三位的数字,转到3
完整的实现代码如下:
#include "iostream"
using namespace std;
char table[20][20]= {"zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninteen" };
char tens[12][20]={"","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninty","hundred","thousand" };
void print(int n)
{
if(n >= 0 && n <= 19)
{
cout<<table[n]; //直接输出19以内的数字
}
else if(n >= 20 && n <= 99 && n%10 == 0) //整十
{
cout<<tens[n/10];
}
else if(n >= 20 && n <= 99) //先输出十位,再输出个位
{
cout<<tens[n/10]<<" "<<table[n%10];
}
else if(n >= 100 && n<= 999)
{
print(n/100);
cout<<" "<<tens[10]<<" "; //输出百位
print(n%100); //递归调用,输出十位和个位
}
else if(n >= 1000 && n <= 999999)
{
print(n/1000);
cout<<" "<<tens[11]<<" "; //输出千位
print(n%1000); //递归调用,输出百位、十位和个位
}
}
int main(void)
{
int n;
while(cin>>n)
{
print(n);
cout<<endl;
}
system("pause");
return 0;
}
运行效果图如下:
下一篇: python翻译器