标签:
1 #include<iostream>
2 #include<string>
3 using namespace std;
4
5 class robot{
6 string name;
7 string type; //型号
8 public:
9 robot(string name = "xxx",string type = "xxx") : name(name),type(type){ //默认构造函数
10 }
11 void out(int a); //英文中每三位数读法相同,所以定义out函数翻译小于1000的整数
12 void tran_int(int n); //将1~1999999999的整数翻译成英文句子
13 ~robot(){ //析构函数
14 };
15 };
16
17 //定义两个全局字符指针数组,存取所需的单词num1[]为1~19
18 static const char *num1[] = {"","one","two","three","four","five","six","seven","eight","nine","ten",
19 "eleven","twelve","thirteen","fourteen","fiveteen","sixteen","seventeen",
20 "eighteen","nineteen"};
21 //num10中为20-90,空了0,1,所以可以直接用num10[n/10]调用,得到n对应的单词
22 static const char *num10[] = {"","","twenty","thirty","forty",
23 "fifty","sixty","seventy","eighty","ninety"};
24 //小于1000整数翻译
25 void robot::out(int a){
26 int b = a%100; //取后两位
27 //若百位不为0,输出百位数加hundred,若此时十位个位均为0,不加and
28 if (a/100 != 0)
29 {
30 cout << num1[a/100] << " hundred ";
31 if (b != 0) //b 应该属于1~19,[20,100);
32 cout << " and ";
33 }
34 //当后两位在20以内,直接调用num1[n],输出
35 if (b < 20)
36 cout << num1[b];
37 else
38 { //先调用num10[b],输出十位数
39 cout << num10[b/10];
40 //个位不为0的应该输出:‘-‘,个位数
41 if (b % 10)
42 cout << "-" << num1[b%10];
43 }
44 }
45
46 void robot::tran_int(int n)
47 {
48 if (n > 1999999999)
49 cout << "dev-C++ 平台无法处理大于1999999999的数!" << endl;
50 else
51 { //三位三位的取出,存在abcd中 1,987,654,321--如此三位三位取出
52 int a = n/1000000000, // 十亿位:1
53 b = (n%1000000000)/1000000, //十亿到百万:987
54 c = (n%1000000)/1000, //百万到前:654
55 d = n%1000; //千位以下:321
56
57 //a不等于0时,输出,并加million,或thousand
58 if (a)
59 {
60 out(a); //因为取出了三位,所以三位三位输出
61 cout << " billion "; //十亿以下
62 }
63 if (b)
64 {
65 out(b);
66 cout << " million "; //百万到十亿
67 }
68 if (c)
69 {
70 out(c);
71 cout << " thousand "; //百万到千
72 }
73 if (d) //千位以下
74 { //距英文语法规则,(前面几位都存在的情况下)最后两位前一定有and,即千位以前要有and
75 if ((d < 100 && a) || b || c)
76 {
77 cout << " and ";
78 }
79 out(d);
80 }
81 cout << endl;
82 }
83 }
84
85 int main(void)
86 {
87 int n;
88 cout << "Input N : ";
89 cin >> n;
90 cout << n << endl;
91 robot brown;
92 brown.tran_int(n);
93 return 0;
94 }
标签:
原文地址:http://www.cnblogs.com/douzujun/p/5657156.html