c++ - 试图让我的程序继续使用 if/else 语句 C++

标签 c++ if-statement

我正在编写一个程序来适应这种情况: 有两个 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/

相关文章:

c++ - gtk - 从文件加载时图像不显示

c++ - Qt连接: Using Lambda Expression Resets Passed int Variable (Weird)

c++ - 我需要一些建议来为我的模拟找到足够的算法

php - 检查多个变量是否都等于 IF 语句中的相同值的简写方法是什么? (PHP)

mysql - 如何形成这个 MySQL 查询?

php - 如何检测同一封电子邮件是否在 2 分钟内多次出现?

c - 编译器是否将 else-if 的这些用法视为同一件事?

c++ - Linux 中的磁盘空间使用情况分析

c++ - 在这种情况下如何测试左值或右值

if-statement - 在 Swift 中的 if 语句中使用多个 let-as