编写代码将给定数字转换为单词(例如1234作为输入应输出一千二百三十四)

Har*_*nan 3 c c++ logic data-structures

编写C/C++/Java代码将给定的数字转换为单词.

例如: - 输入:1234

输出:一千二百三十四.

输入:10

输出:十

是否需要数字0到10的完整开关盒.

在每个数字名称之后添加"青少年"(例如:14:4"青少年".)从14到19.

而不是添加"ty"和20到99范围内的数字的数字名称.

等等.

我认为必须有一些更好的方法来解决这个问题.

C代码是首选.

小智 15

#include<iostream>
using namespace std;
void expand(int);
int main()
{
    int num;
    cout<<"Enter a number : ";
    cin>>num;
    expand(num);
}
void expand(int value)
{
    const char * const ones[20] = {"zero", "one", "two", "three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
    "eighteen","nineteen"};
    const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",
    "eighty","ninety"};

    if(value<0)
    {
        cout<<"minus ";
        expand(-value);
    }
    else if(value>=1000)
    {
        expand(value/1000);
        cout<<" thousand";
        if(value % 1000)
        {
            if(value % 1000 < 100)
            {
                cout << " and";
            }
            cout << " " ;
            expand(value % 1000);
        }
    }
    else if(value >= 100)
    {
        expand(value / 100);
        cout<<" hundred";
        if(value % 100)
        {
            cout << " and ";
            expand (value % 100);
        }
    }
    else if(value >= 20)
    {
        cout << tens[value / 10];
        if(value % 10)
        {
            cout << " ";
            expand(value % 10);
        }
    }
    else
    {
        cout<<ones[value];
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)