2012-12-17 30 views
0

我正在寫一個程序,以適應這種情況: 有兩個孩子。他們都添加自己的錢在一起,以決定是否要錢花在冰淇淋或糖果。如果他們有超過20美元的話,把它全部花在冰激凌上(1.50美元)。否則,花在糖果上(50美元)。顯示他們將購買的冰淇淋或糖果的數量。試圖讓我的計劃繼續使用if/else語句C++

I've written my code here: 

#include<iostream> 
#include <iomanip> 
using namespace std; 

//function prototypes 
void getFirstSec(double &, double &); 
double calcTotal(double, double); 

int main() 
{ 

//declare constants and variables 
double firstAmount = 0.0; 
double secondAmount = 0.0; 
double totalAmount = 0.0; 
const double iceCream = 1.5; 
const double candy = 0.5; 
double iceCreamCash; 
double candyCash; 
int iceCreamCount = 0; 
int candyCount = 0; 


//decides whether to buy ice cream or candy 
getFirstSec(firstAmount, secondAmount); 
totalAmount = calcTotal(firstAmount, secondAmount); 

if (totalAmount > 20) 
{ 
     iceCreamCash = totalAmount; 
     while (iceCreamCash >= 0) 
     { 
       iceCreamCash = totalAmount - iceCream; 
       iceCreamCount += 1; 
     } 
     cout << "Amount of ice cream purchased : " << iceCreamCount; 
} 
else 
{ 
     candyCash = totalAmount; 
     while (candyCash >= 0) 
     { 
       candyCash = totalAmount - candy; 
       candyCount += 1; 
     } 
     cout << "Amount of candy purchased : " << candyCount; 
} 
} 
// void function that asks for first and second amount 
void getFirstSec(double & firstAmount, double & secondAmount) 

{ 
cout << "First amount of Cash: $"; 
cin >> firstAmount; 
cout << "Second amount of Cash: $"; 
cin >> secondAmount; 
return; 
} 
// calculates and returns the total amount 
double calcTotal(double firstAmount , double secondAmount) 
{ 
    return firstAmount + secondAmount; 
} 

我輸入第一個和第二個數量,但它不會繼續到if/else部分。任何人都可以啓發我問題是在這裏?謝謝!

回答

6
while (iceCreamCash >= 0) 
    { 
      iceCreamCash = totalAmount - iceCream; 
      iceCreamCount += 1; 
    } 

該循環將永遠不會結束。在循環不得使在每次循環iceCreamCash下降。也許你的意思是:

while (iceCreamCash >= 0) 
    { 
      iceCreamCash = totalAmount - iceCream * iceCreamCount; 
      iceCreamCount += 1; 
    } 
+0

...和哪些可以計算沒有*循環*也。 – Nawaz

+1

重要的教訓:永遠不要認爲不會離開一段代碼意味着你永遠不會啓動它。它確實進入了「if/else」部分。 –

+0

或者你可以使用'iceCreamCash - =冰淇淋;'。 – DanS