如何防止此循环? C ++

时间:2016-11-02 19:27:24

标签: c++

我是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;
    }

2 个答案:

答案 0 :(得分:2)

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

  • 无意中将终止条件boolyes重新分配给:true,而不是检查其值==,而不是作业=

  • yes循环中没有修改值while

可能的更新是:

#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;
}

此外,请注意未初始化的变量:xyza并考虑一个正确的默认值,以指示可能的错误结果。< / p>

最后,在进行计算时:1 + y / a不明确,它可能意味着:(1 + y) / a和:1 + (y / a),请在括号中强制执行所需顺序的优先顺序。

答案 1 :(得分:1)

您没有修改变量"2016-11-02 19:18:57.149197306 +0000 UTC"的值。它始终设置为yes

相关问题