[英]How do I prevent this loop? C++
我是C ++的新手,并且通常会发生堆栈溢出,因此,如果在某个地方出错,请原谅。 我在下面发布了我的代码,但是我的问题是,当计算完成后我在输入yes
或no
时, 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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.