【问题标题】:Trying to get my program to continue with an if/else statement C++试图让我的程序继续使用 if/else 语句 C++
【发布时间】:2012-12-04 19:40:28
【问题描述】:

我正在编写一个程序来适应这种情况: 有两个孩子。他们俩把钱加在一起,决定是否把钱花在冰淇淋或糖果上。如果他们有超过 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 部分。谁能告诉我这里的问题是什么?谢谢!

【问题讨论】:

    标签: c++ if-statement


    【解决方案1】:
       while (iceCreamCash >= 0)
       {
              iceCreamCash = totalAmount - iceCream;
              iceCreamCount += 1;
       }
    

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

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

    【讨论】:

    • ... 也可以在没有 loop 的情况下计算。
    • 重要的教训:永远不要假设不留下一段代码就意味着你从未开始过它。它确实进入了“if/else”部分。
    • 或者你可以使用iceCreamCash -= iceCream;
    猜你喜欢
    • 2022-11-03
    • 2022-01-06
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多