Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

后端 未结 8 642
名媛妹妹
名媛妹妹 2021-02-01 11:37

Write C/C++/Java code to convert given number into words.

eg:- Input: 1234

Output: One thousand two hundred thirty-four.

Input: 10

Output: Ten

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 11:52

    #include
    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<

提交回复
热议问题