首页 > 解决方案 > 程序在一段时间后结束并忽略之后发生的事情

问题描述

嗨,我想知道是否有人可以帮助解决这个问题,问题是在程序中不工作/正在运行之后会发生什么。我的代码有问题还是我必须做的事情?谢谢。

#include <iostream>
using namespace std;

int main() {
    
    int priceArticle;
    int taxPercent;
    int total = 0;
    int totalAfterTax;
    int valueFinish = -1;
    bool isTrue = true;
    bool isTaxesTrue = true;

    while (isTrue = true) {
        cout << "How much money was the cost of your item? " << endl;
        cin >> priceArticle;
        
        if (priceArticle != valueFinish) {
            total += priceArticle;
            cout << total << endl;
        }
        if (priceArticle == valueFinish) {
            cout <<  "Your total before taxes is " << total << endl;
            isTrue = false;
            return isTrue;
        }
    }       

   
    cout << "What's the percent of taxes you must pay?" << endl;
    cin >> taxPercent;
    
    

    

}

标签: c++

解决方案


您的代码和逻辑中几乎没有错误:

  1. 首先,您在 while 循环中的条件不写为条件。您编写了while(isTrue = true) 而不是使用条件运算符 ==。这可能会导致您描述的问题,即代码卡在 while 循环中。

  2. 第二个 if 语句条件无法满足(逻辑上),因为您设置了 valueFinish = -1

  3. 您在不需要时使用了 return isTrue,您不在必须返回值的函数中。 是真=假;就是你所需要的。

  4. 我不确定您的任务是什么,但条件似乎存在逻辑错误。您将priceArticlevalueFinish进行比较,而不是累积变量total,您基本上根本不使用它。我想一旦总价值超过某个条件,你就想摆脱这段时间。

这是实现我上面提到的所有要点的代码:


#include <iostream>
using namespace std;

int main() {
    
    int priceArticle;
    int taxPercent;
    int total = 0;
    int totalAfterTax;
    int valueFinish = 200;
    bool isTrue = true;
    bool isTaxesTrue = true;

    while (isTrue == true) {
        cout << "How much money was the cost of your item? " << endl;
        cin >> priceArticle;
        
        if (total+priceArticle < valueFinish) {
            total += priceArticle;
            cout << total << endl;
        }
        else {
            total += priceArticle;
            cout <<  "Your total before taxes is " << total << endl;
            isTrue = false;
            // return isTrue;
        }
    }       

   
    cout << "What's the percent of taxes you must pay?" << endl;
    cin >> taxPercent;
}
     

推荐阅读