簡體   English   中英

如何防止此循環? C ++

[英]How do I prevent this loop? 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;
    }

您的代碼的行為可能是由於:

  • 意外地將終止條件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;
}

此外,請注意未初始化的變量: xyza並考慮適當的默認值,該值將指示可能的錯誤結果。

最后,隨着計算: 1 + y / a是模棱兩可的,它可能意味着: (1 + y) / a和: 1 + (y / a) ,在括號中放入想要的順序以強制執行優先級。

您沒有修改變量yes的值。 始終設置為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM