如何防止这种循环?c++

How do I prevent this loop? C++

本文关键字:c++ 循环 何防止      更新时间:2023-10-16

我不熟悉c++和堆栈溢出,所以如果我在某个地方犯了错误,请原谅我。我在下面发布了我的代码,但我的问题是,当我在计算完成后输入yesno时,no应该结束程序(我仍在工作),yes应该为另一个计算设置它。

然而,我最终与一个小故障循环。

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    bool b;
    bool yes = b;
    do {
        float x;
        float y;
        float z;
        float a;
        cout << "Enter The amount you are investing:" << endl;
        cin >> x;
        cout << "Enter the rate:" << endl;
        cin >> y;
        cout << "Enter the investment period (years):" << endl;
        cin >> z;
        cout << "Enter the compounding period:" << endl;
        cin >> a;
        cout << pow((1 + y / a), (a*z))*x << endl << "Want to do another? (yes/no)";
        cin >> b;
        cin.ignore();
    } while (yes = true); {
        cin.clear();
        if (b = yes) {
        }
        else {
            }
        }
        return 0;
    }

您的代码的行为可能是由于:

  • 无意地将终止条件bool的值:yes重赋给:true,而不是检查它的值,这是通过==完成的,而不是通过赋值=完成的。

  • while循环中不修改yes的值。

一个可能的更新是:

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    // initialise the sentinel
    bool yes = true;
    do {
        // define variables
        float x, y, z, a;
        // read input
        cout << "Enter The amount you are investing:" << endl;
        cin >> x;
        cout << "Enter the rate:" << endl;
        cin >> y;
        cout << "Enter the investment period (years):" << endl;
        cin >> z;
        cout << "Enter the compounding period:" << endl;
        cin >> a;
        cout << pow((1 + y / a), a * z) * x << endl;
        // redo calculation or exit
        cout << "Want to do another? (yes/no)";
        cin >> yes;
        // check termination condition
    } while (yes == true);
    return 0;
}

另外,注意未初始化的变量:x, y, z, a,并考虑一个适当的默认值,这将表明可能错误的结果。

最后,在计算中:1 + y / a是有歧义的,它可以同时表示:(1 + y) / a和:1 + (y / a),用括号来按照需要的顺序强制优先级。

不能修改变量yes的值。它总是设置为true