1. 程式人生 > >阿拉伯數字轉換為英語

阿拉伯數字轉換為英語

題目描述

Jessi初學英語,為了快速讀出一串數字,編寫程式將數字轉換成英文:
如22:twenty two,123:one hundred and twenty three。

說明:
數字為正整數,長度不超過九位,不考慮小數,轉化結果為英文小寫;
輸出格式為twenty two;
非法資料請返回“error”;
關鍵字提示:and,billion,million,thousand,hundred。

#include<iostream>
//#include<vector>
//#include<algorithm>
using namespace
std; string num1[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; string num2[] = {"ten","eleven","twelve","thirteen","fourteen", "fifteen","sixteen","seventeen","eighteen","nineteen"}; string num3[] = {"twenty","thirty","forty","fifty"
, "sixty","seventy","eighty","ninety"}; string translate(long); string Parse(long num) {//把數字以3位數為單位進行切分 string res=""; long billion = num / 1000000000;//十億部分 if(billion != 0){ res.append(translate(billion) + " billion ");//翻譯十億部分 } num = num % 1000000000;//百萬部分 long million = num / 1000000
; if(million != 0){ res.append(translate(million) + " million ");//翻譯百萬部分 } num = num % 1000000;//千部分 long thousand = num / 1000; if(thousand != 0){ res.append(translate(thousand) + " thousand ");//翻譯千部分 } num = num % 1000;//百部分 if(num != 0){ res.append(translate(num));//翻譯百部分 } int len=res.size();//去除字串後面的空格 if(res[len-1]==' ') res.resize(len-1); return res; } string translate(long num) {//處理三位數 string s=""; long h = num / 100;//百位處理 if(h != 0){ s.append(num1[(int) h] + " hundred"); } num = num % 100;//十位部分 long k = num / 10; if(k != 0){ if(h != 0)//如果有百位別忘了加and s.append(" and "); if(k == 1){//若十位為1,連同個位一起翻譯 long t = num % 10; s.append(num2[(int)t]); } else{//否則,十位和個位分別單獨翻譯 s.append(num3[(int)k - 2] + " "); if(num % 10 != 0) s.append(num1[(int)(num % 10)]); } } else if(num % 10 != 0){//如果沒有十位部分,直接翻譯個位部分 if(h != 0) s.append(" and "); s.append(num1[(int)(num % 10)]); } int len=s.size();//去除字串後面的空格 if(s[len-1]==' ') s.resize(len-1); return s; } int main() { long num; while(cin>>num){ cout<<Parse(num)<<endl; } return 0; }