一、题目:
描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
本题含有多组输入数据。
二、输入输出示例:
![](https://i-blog.csdnimg.cn/blog_migrate/3c82a2e5d9624e2f466f7dce14eeabfc.png)
三、代码:
#include<iostream>
using namespace std;
#include<vector>
#include<string>
vector<string> v1 = {"one","two","three","four","five","six","seven","eight","nine",
"ten","eleven","twelve","thirteen","fourteer","fifteen","sixteen",
"seventeen","eighteen","nineteen"};
vector<string> v2 = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"};
void LessThan100(int num)
{
if(num<=19)
{
cout<<v1[num-1];
}
else if(num % 10 == 0)
{
cout<<v2[num/10-2];
}
else
{
cout<<v2[num/10-2]<<" "<<v1[num%10-1];
}
}
void LessThan1000(int num)
{
cout<<v1[num/100-1]<<" "<<"hundred";
if(num % 100 != 0)
{
cout<<" and ";
num %=100;
LessThan100(num);
}
}
void LessThan1000000(int num)
{
if(num / 1000 >=100)
{
LessThan1000(num/1000);
}
else
{
LessThan100(num/1000);
}
cout<<" thousand";
if(num % 1000 != 0)
{
num %= 1000;
if(num < 10)
{
cout<<" and ";
LessThan100(num);
}
if(num < 100)
{
cout<<" ";
LessThan100(num);
}
if(num < 1000 && num >= 100)
{
cout<<" ";
LessThan1000(num);
}
}
}
void LessThan1000000000(int num)
{
if(num/1000000 >= 100)
{
LessThan1000(num/1000000);
}
if(num/1000000 < 100)
{
LessThan100(num/1000000);
}
cout<<" million";
if(num % 1000000 >= 1000)
{
cout<<" ";
LessThan1000000(num % 1000000);
}
else if(num % 1000000 >= 100)
{
cout<<" ";
LessThan1000(num % 1000000);
}
else if(num % 1000000 == 0)
{
return;
}
else
{
cout<<" and ";
LessThan100(num % 1000000);
}
}
int main()
{
long num;
while(cin>>num)
{
if(num<100)
{
LessThan100(num);
}
else if(num < 1000)
{
LessThan1000(num);
}
else if(num < 1000000)
{
LessThan1000000(num);
}
else if(num < 1000000000)
{
LessThan1000000000(num);
}
else
{
cout<<"error";
}
cout<<endl;
}
system("pause");
return 0;
}