我正在编写一个程序来适应这种情况: 有两个 child 。他们将自己的钱加在一起,决定是否将钱花在冰淇淋或糖果上。如果他们有超过 20 美元,则将其全部花在冰淇淋上(1.50 美元)。否则,将其全部花在糖果上($.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 部分。谁能告诉我这里的问题是什么?谢谢!
最佳答案
while (iceCreamCash >= 0)
{
iceCreamCash = totalAmount - iceCream;
iceCreamCount += 1;
}
这个循环永远不会结束。循环中的任何内容都不会使 iceCreamCash
在循环的每次迭代中减少。也许你的意思是:
while (iceCreamCash >= 0)
{
iceCreamCash = totalAmount - iceCream * iceCreamCount;
iceCreamCount += 1;
}
关于c++ - 试图让我的程序继续使用 if/else 语句 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13918749/