循环失败

Looping failure

我需要让程序循环直到用户输入 "XXXX" 作为名称。问题是,我的代码最多只循环一次然后退出。我试过搞乱 do ... whiles 一整天,但似乎无法弄清楚,但我觉得我真的很接近!

编辑: 你们真棒!进行了两项更改,但现在它会跳过名称提示并直接进入存款提示。我如何让它在循环中包含名称提示?

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main() {

string name, XXXX;
float deposit, time, interest, total, totinterest;
int compound;

cout << left;

int flag = 0;

do {

    cout << "Enter your name or XXXX to stop: ";
    getline(cin, name);
    cout << name << " enter the following information: " << endl;


    if (name == "XXXX"){
        flag = 1;
    }else 
    {

        cout << setw(60) << "\tAmount on deposit: ";
        cin >> deposit;
        if (!deposit || deposit < 0){
            cout << "\tPlease enter a positive number! ";

        }

        cout << setw(60) << "\tYears on deposit: ";
        cin >> time;
        if (!time || time < 0){
            cout << "\tPlease enter a positive number! ";
            return(0);
        }

        cout << setw(60) << "\tNumber of times the interest is compounded per year: ";
        cin >> compound;
        if (!compound || compound < 0){
            cout << "\tPlease enter a positive number! ";
            return(0);
        }

        if (time >= 5)
            interest = .045;
        else if (time >= 4)
            interest = .04;
        else if (time >= 3)
            interest = .035;
        else if (time >= 2)
            interest = .025;
        else if (time >= 1)
            interest = .02;
        else if (time < 1)
            interest = .015;

        total = (deposit)*pow((1 + interest / compound), (compound * time));
        totinterest = total - deposit;

        cout << left << setprecision(2) << fixed;
        cout << endl;
        cout << setw(15) << "Name " << setw(14) << "Years" << setw(18) << "Deposit Amount" << setw(18) << "Interest Earned " << setw(18) << "Total" << endl;
        cout << "===============================================================================" << endl;
        cout << setw(15) << name << setw(14) << time << setw(1) << "$" << setw(17) << deposit << setw(1) << "$" << setw(17) << totinterest << setw(1) << "$" << setw(18) << total << endl;
        cout << endl;
        cout << "Thank you for using tax program. Have a nice day. " << endl;
        return(0);

    }

} while (flag = 0);

}

因为您在 while 条件下使用 = 而不是 ==

flag = 0 更改为 !flagflag==0

除此之外,您还有 return 0 这是无条件的。 return 语句将使程序无论如何退出。

return(0) 会让你脱离主线。删除该行并重试。

您的 else 子句中有一个 return(0);。此外,您的 while 循环中有 = 而不是 ==,这(在删除 return 语句之后)是无限循环的秘诀。

return(0) 将退出 main() 并且程序将终止。因此,将其从源中删除。

此外 while (flag = 0) 中的条件将始终 return false。将其更改为 while (flag == 0) 否则会导致 循环仅迭代一次 .

最后,pow() 函数需要 <math.h>

#include <math.h>

你必须包括

#include <math.h> 

让你的 pow 函数正常工作。我收到未定义 pow 的错误。

首先,您希望 while 条件为 while(flag == 0) 而不是 while (flag = 0)

此外,如果用户输入的时间或存款或化合物的值无效(例如小于 0),那么您的代码会打印出错误消息并退出。相反,您想在那里放置一个 while 循环,只要用户不断提供不正确的输入,它就会不断提示用户进行有效输入。

最后,您想使用 myString.compare(otherString) 之类的东西来代替 == 运算符