人民幣金額大寫問題
阿新 • • 發佈:2019-01-10
問題描述
在與財務相關的應用中,經常會用到人民幣金額的大寫,比如發票的列印程式。本題的任務是:從鍵盤輸入一個十億以內的正整數(int 型別),把它轉換為人民幣金額大寫(不考慮使用者輸入錯誤的情況)
比如,使用者輸入: 35201,程式輸出:叄萬伍仟貳佰零壹
使用者輸入: 30201,程式輸出:叄萬零貳佰零
演算法設計
主要是利用棧來實現,因為棧的特點是先入後出,而我們通過計算機(整除和求餘)讀入是從低位到高位讀入,而輸出的時候是從高位往低位讀。關於權和零的問題,因為比較特殊當size == 4
或size==8
,直接輸出‘萬’、‘億’,多個零的情況可以通過一個while
演算法實現
採用棧的資料結構(簡單版本)
class numStack{
protected:
int *upper; // 存每個數字
int size; // 存有多少個數字
public:
numstack(){
upper = new int[20]; // 題目說明了最大10億
size = 0;
} // 建構函式
~numstack(){
delete []upper;
} // 解構函式
void Push(const int n){
upper[size++] = n;
return ;
} // 入棧
int Top(){
int i = size - 1;
return upper[i];
} // 取棧頂元素
void Pop(int &n){
n = upper[size-1];
size--;
return ;
} // 出棧
int theSize(){
return size;
} // size 為protected型別,只能通過函式訪問
主函式
int main()
{
int money;
numstack myStack;
cout<<"請輸入金額:";
while(cin>>money){
string upchar[9] = {"壹","貳","叄","肆","伍","陸","柒","捌","玖"};
string unit[4] = {"十","百","千","萬"};
int now = 0;
while(money != 0){
myStack.Push(money%10); // 依次入棧
money = money / 10;
}
while(myStack.theSize()!=0){
if(myStack.Top()!=0){ // 看棧頂元素是否為零
myStack.Pop(now); // 是的話出棧並在下面把權表示出來
cout<<upchar[now-1];
if(myStack.theSize() == 8){
cout<<"億";
} else if (myStack.theSize()==0){
cout<<"";
}else{
cout<<unit[(myStack.theSize()-1)%4]; // 輸出權
}
} else{
while(myStack.Top()==0){
myStack.Pop(now);
if(myStack.theSize() ==4 && now==0){ // 輸出當萬位為0的時候‘萬’權
cout<<"萬";
}
}
if(myStack.theSize()!=0){
cout<<"零"; // 中間的零隻輸出一個
}
}
}
cout<<endl;cout<<"請輸入金額:"; // 格式控制
}
return 0;
}