數字翻譯器及其實現

來源:互聯網
上載者:User

【問題描述】
輸入一個正整數N(N最大是4位元),輸出它的英文表達。
【範例】
輸入:1
輸出:one
又輸入:12
輸出:twelve
右輸入:135
輸出:one hundred thirty five

思路:1、首先19以內的數字,可以直接輸出。。

2、20~~~99以內的數字,整十的整數可以直接輸出。否則,除以10輸出十位元字,與10模數輸出個位元字。

3、100~~~999以內的數字,除以100輸出百位元字,與100模數得到一個兩位的數字,轉到2

4、1000~~~9999以內的數字,除以1000輸出千位元字,與1000模數得到一個三位的數字,轉到3

完整的實現代碼如下:

#include "iostream"using namespace std;char table[20][20]= {"zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninteen" };char tens[12][20]={"","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninty","hundred","thousand" };void print(int n){if(n >= 0 && n <= 19){cout<<table[n];         //直接輸出19以內的數字}else if(n >= 20 && n <= 99 && n%10 == 0)     //整十{cout<<tens[n/10];}else if(n >= 20 && n <= 99)          //先輸出十位,再輸出個位{cout<<tens[n/10]<<" "<<table[n%10];}else if(n >= 100 && n<= 999){print(n/100);cout<<" "<<tens[10]<<" ";    //輸出百位print(n%100);                //遞迴調用,輸出十位和個位}else if(n >= 1000 && n <= 999999){print(n/1000);cout<<" "<<tens[11]<<" ";    //輸出千位print(n%1000);               //遞迴調用,輸出百位、十位和個位}}int main(void){int n;while(cin>>n){print(n);cout<<endl;}system("pause");return 0;}

運行如下:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.