2012-09-15 56 views
2

因此,我正在嘗試構建此程序,我想從用戶那裏接受一個總金額和金額爲付款金額的輸入。現在,餘額應該分解爲10美元,5美元,1美元,季度,硬幣和鎳。但是下面的程序/代碼告訴我餘額中有四分之一,一角硬幣和五分硬幣的總數,而不是餘下的。例如 。如果總金額爲5.76,支付金額爲15美元,那麼它應該顯示零10美元,1美元5美元,4美元1美元,0美元25美元,2美元10美元,0美元0.05美元和4美元0.01美元。在C++硬幣更改算法中計算錯誤

請告訴我這裏的代碼有什麼問題嗎?

+1

你試過在一個調試器中運行呢? –

+0

你在哪裏計算10美元,5美元和1美元的賬單數量? –

+0

當你所有的數據都用整數表示時,爲什麼你會期望'.01'被顯示? –

回答

2

最簡單的方法是將數字作爲浮點數乘以100,然後將其保存爲int。

#include <iostream> 

using namespace std; 

int main () 
{ 
    float userNUmber; 
    int change, quarters, dimes, nickels, pennies; // declare variables 
    cout <<"Enter the amount of money: "; 
    cin >> userNUmber; // input the amount of change 
    change = userNUmber * 100; 
    quarters = change/25; // calculate the number of quarters 
    change = change % 25; // calculate remaining change needed 
    dimes = change/10; // calculate the number of dimes 
    change = change % 10; // calculate remaining change needed 
    nickels = change/5; // calculate the number of nickels 
    pennies = change % 5; // calculate pennies 

    cout << "\nQuarters: " << quarters << endl; // display # of quarters 
    cout << " Dimes: " << dimes << endl; // display # of dimes 
    cout << " Nickels: " << nickels << endl; // display # of nickels 
    cout <<" Pennies: " << pennies << endl; // display # of pennies 
    system("Pause"); 
    return (0); 
} 

也做在一個循環是這樣的

#include <iostream> 
#include <vector> 
#include <string> 
using namespace std; 


int main () 
{ 
    float userNUmber; 
    int change, quarters, dimes, nickels, pennies; // declare variables 

    cout <<"Enter the amount of money: "; 
    cin >> userNUmber; // input the amount of change 
    change = userNUmber * 100; 

    vector<int> coins(4, 0); 
    coins[0] = 25; coins[1] = 10; coins[2] = 5; coins[3] = 1; 
    vector<string> coinsName(4, ""); 
    coinsName[0] = "Quaters"; coinsName[1] = "Dimes"; coinsName[2] = "Nickels"; coinsName[3] = "Pennies"; 

    for(size_t i = 0; i < coins.size(); ++i) 
    { 
     int numberOfCoins = change/coins[i]; // calculate the number of quarters 
     change = change % coins[i]; // calculate remaining change needed 
     cout << coinsName[i] << ": " << numberOfCoins << endl; // display # of quarters 
    } 
    system("Pause"); 
    return (0); 
} 
+0

非常感謝..現在正常工作:) – user15169

+1

@DownVoter爲什麼? – Caesar

+0

@caeasar ..這也可以在for循環中完成? – user15169