2016-02-06 30 views
-7

該代碼工作不正常! 我是C++的新手,我的任務是編寫一個代碼,從用戶(金額)中獲取一個值,然後將其轉換爲「宿舍= 25美分,硬幣= 10美分,鎳幣= 5美分,便士= 1美分「 所以例如,當我輸入值7.47我應該得到29季度,2角錢,0鎳幣,2便士等等...我的問題是,我已經嘗試了很多值,它工作得很好,但是當我嘗試價值9.53我應該得到38個季度,0個角錢,0個鎳幣和3個便士,但相反,我得到38個季度,0個角錢,0個鎳幣和2個便士 同樣的錯誤發生在我嘗試8.53時,但當我嘗試6.53,5.53 .4.53它運作良好!我現在很困惑,所以請幫助!C++,一個代碼來獲得一筆錢轉換成宿舍,硬幣,鎳幣,便士

`#include<iostream> 
using namespace std; 
int main() 
{ 
    double money, c_money, quarters, dimes, nickels, pennies, remainder; char response; 
    new_input:          
    cout << " Enter the amount of money to be converted : " << endl; 
    cin >> money; 
    while (money < 0) 
    {                    
     cout << " Invalid input , please enter a non-negative value " << endl;  
     cin >> money; 
    } 
    c_money = money * 100;            
    quarters = (int)c_money/25; 
    remainder = (int)c_money % 25; 
    dimes = (int)remainder/10; 
    remainder = (int)remainder % 10; 
    nickels = (int)remainder /5; 
    remainder = (int)remainder % 5; 
    pennies = (int)remainder ; 
    cout << endl; 
    cout << " The amount of money entered could be represented as : " << endl; 
    cout << "*****************************************************" << endl; 
    cout <<" Number of quarters : "<< quarters << endl; 
    cout <<" Number of dimes : "<<dimes << endl; 
    cout <<" Number of nickels : "<< nickels << endl; 
    cout <<" Number of pennies : "<< pennies << endl<<endl; 
    cout << "Do you want to enter more values ?? type , y or n and press Enter ! " << endl;  
    cin >> response; 
    if (response == 'y') 
    { 
     goto new_input; 
    } 
    else { cout << " Thanks for using our app !! " << endl << endl; } 
    return 0; 
}` 
+3

在這種情況下使用'double'是錯誤的。使用'goto'幾乎總是weong。 –

+0

這項任務非常常見,遍佈互聯網的成千上萬個問題以及不同的解決方案。 –

+0

好吧,我同意double是太多了,goto語句已過時,但是在添加此goto之前我也遇到了同樣的問題 –

回答

2

你是double不準確的受害者。您的代碼可能會在99%的情況下工作,但不準確性會在餘下的1%內...

我建議您在需要進行精確計算時不要使用double。關於每一分錢都很重要的金錢。用int代替它,將它乘以100(所以你不會丟失小數部分),並用整數進行所有計算。

+0

該作業正在考慮輸入類似於9.75,用戶將以小數部分的形式輸入,因此如果將所有內容都轉換爲int而不是double,則會從代碼的最開始就會丟失數據,用戶進入9.75時,它將被隱式轉換爲9,導致損失0.75 –

+0

不,您沒有正確閱讀我寫的內容。你乘以100,所以你得到975. – radoh

+0

我沒看過它,但我需要得到的價值,然後我乘以它! ,你可以爲你的建議書寫一些代碼,也許我還是錯了嗎? –