0

我正在编写一个程序来适应这种情况:有两个孩子。他们俩把钱加在一起来决定是否把钱花在冰淇淋或糖果上。如果他们有超过 20 美元,把所有的钱都花在冰淇淋上(1.50 美元)。否则,把所有的钱都花在糖果上(0.50 美元)。显示他们将购买的冰淇淋或糖果的数量。

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 部分。谁能告诉我这里的问题是什么?谢谢!

4

1 回答 1

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

这个循环永远不会结束。循环中的任何内容都不会在循环iceCreamCash的每次迭代中减少。也许你的意思是:

   while (iceCreamCash >= 0)
   {
          iceCreamCash = totalAmount - iceCream * iceCreamCount;
          iceCreamCount += 1;
   }
于 2012-12-17T17:14:38.963 回答