2017-09-30 230 views
-2

第二次提示cin我需要該程序充當自動售貨機,保持總運行並確定更改(如果適用)。while while循環處於無限循環時,不會通過

#include <iostream> 
using namespace std; 

int main() 
{ 

    cout << "A deep-fried twinkie costs $3.50" << endl; 
    double change, n = 0, d = 0, q = 0, D = 0, rTotal = 0; 

    do 
    { 
     cout << "Insert (n)ickel, (d)ime, (q)uarter, or (D)ollar: "; 
     cin >> rTotal; 
     if (rTotal == n) 
      rTotal += 0.05; 
     if (rTotal == d) 
      rTotal += 0.10; 
     if (rTotal == q) 
      rTotal += 0.25; 
     if (rTotal == D) 
      rTotal += 1.00; 

     cout << "You've inserted $" << rTotal << endl; 


     cout.setf(ios::fixed); 
     cout.precision(2); 


     } while (rTotal <= 3.5); 

     if (rTotal > 3.5) 
      change = rTotal - 3.5; 


      return 0; 
} 
+1

比較浮動和雙打:https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison –

+0

你目前需要兩個不同的變量插入的硬幣和總金額。 – mkrieger1

+0

此外,如果用戶輸入的字母等於0,那麼您目前正在檢查所有情況,這從來都不是真的。 – mkrieger1

回答

0

你正在做一些事情錯了。首先,您需要有一個變量來讀取選項的字符(n,d,q和D)。您還需要將這些字母用作字符(即'n'等)。然後,您需要將從輸入中讀取的選項與字符進行比較,而不是插入的總數。最後,如果用戶已經插入$ 3.50,則不需要再次迭代,因此條件應該是rTotal < 3.5

下面是與更正代碼:

#include <iostream> 
using namespace std; 

int main() { 
    cout << "A deep-fried twinkie costs $3.50" << endl; 
    double change, n = 0, d = 0, q = 0, D = 0, rTotal = 0; 
    char op; 
    do { 
     cout << "Insert (n)ickel, (d)ime, (q)uarter, or (D)ollar: "; 
     cin >> op; 
     if (op == 'n') 
      rTotal += 0.05; 
     else if (op == 'd') 
      rTotal += 0.10; 
     else if (op == 'q') 
      rTotal += 0.25; 
     else if (op == 'D') 
      rTotal += 1.00; 
     cout.setf(ios::fixed); 
     cout.precision(2); 
     cout << "You've inserted $" << rTotal << endl; 
    } while (rTotal < 3.5); 
    if (rTotal > 3.5) 
     change = rTotal - 3.5; 
    return 0; 
} 

如果你想數用戶已經插入硬幣,然後if語句括號添加到加1到相應的變量,如果這種硬幣插入。

+0

非常感謝!我正準備在這個項目上失去希望。你是男人中的聖人。 –

+0

如果解決了您的問題,請接受答案 –