我正在编写一个适合这种情况的程序:有两个孩子.他们都把钱加在一起决定是否把钱花在冰淇淋或糖果上.如果他们有超过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;
}
Run Code Online (Sandbox Code Playgroud)
我输入了第一个和第二个金额,但它没有继续到if/else部分.任何人都可以告诉我这里的问题是什么?谢谢!
while (iceCreamCash >= 0)
{
iceCreamCash = totalAmount - iceCream;
iceCreamCount += 1;
}
Run Code Online (Sandbox Code Playgroud)
这个循环永远不会结束.循环中的任何内容iceCreamCash都不会减少循环的每次迭代.也许你的意思是:
while (iceCreamCash >= 0)
{
iceCreamCash = totalAmount - iceCream * iceCreamCount;
iceCreamCount += 1;
}
Run Code Online (Sandbox Code Playgroud)