代码如下:
#include<iostream>
#include<string>
#include<iomanip>
#include<sstream>
using namespace std;
class Num2Clause
{
private:
int num;//待转化数字
//字符串数组
static const string onesNames[];//个位数
static const string tenAboves[];//10-19
static const string tensNames[];//整十数字
static const string levelNames[];//数量级
public:
//构造函数
Num2Clause(int num)
{
this->num = num;
}
//仅处理两位非负数:
string toString2D()
{
if (num < 10)
return onesNames[num];
else if (num < 20)
return tenAboves[num - 10];
else if (num % 10 == 0)
return tensNames[num / 10];
else
//字符串拼接 (递归法)
return tensNames[num / 10] + " " + (new Num2Clause(num % 10))->toString2D();
//或者用加法:
// return tensNames[num / 10] + " " + onesNames[num % 10];
}
//仅处理三位非负数:
string toString3D()
{
if (num < 100)
return toString2D();
else if (num % 100 == 0)
return onesNames[num / 100] + " " + levelNames[0];
else
return onesNames[num / 100] + " " + levelNames[0] + " and " + (new Num2Clause(num % 100))->toString3D();
}
//处理 2147483647 以内的实数
string toString()//toString中可调用toString2D ,但可能需做修改
{
int len = to_string(num).length();//数字位数
int lev = (len - 1) / 3;//数字等级
//是否为负数
if (num < 0)
return "minus " + (new Num2Clause(-num))->toString();
else
{
if (lev == 0)
return toString3D();
else if (num % (int)pow(1000, lev) == 0)
return (new Num2Clause(num / (int)pow(1000, lev)))->toString() + " " + levelNames[lev];
else
return (new Num2Clause(num / (int)pow(1000, lev)))->toString() + " " + levelNames[lev]
+ " "+ (new Num2Clause(num % (int)pow(1000, lev)))->toString();
}
}
static void plainTest()
{
//简单class测试函数
for (int n = 0; n < 100; n += 3)
{
cout << setw(5) << n << " => \"" << (new Num2Clause(n))->toString() << "\"" << endl;
}
}
static void interactiveTest(int n = 7)
{
//交互式测试
cout << (new Num2Clause(n))->toString() << endl;
cout << " Input New Number Here : ";
cin >> n;
return interactiveTest(n);
}
};
const string Num2Clause::onesNames[] = { "zero" , "one" , "two" ,"three" , "four",
"five" , "six" , "seven" , "eight" , "nine" , "ten" };
const string Num2Clause::tenAboves[] = { "ten" , "eleven" , "twelve" , "thirteen" , "fourteen",
"fifteen" , "sixteen" , "seventeen" , "eighteen" , "nineteen" };
const string Num2Clause::tensNames[] = { "zero" , "ten" , "twenty" , "thirty" , "forty",
"fifty" , "sixty" , "seventy" , "eighty" , "ninety" };
const string Num2Clause::levelNames[] = { "hundred","thousand","million","billion","trillion" };
int main()
{
Num2Clause::plainTest();
Num2Clause::interactiveTest();
return 0;
}