当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?
My Quadratic equation code terminates when I enter a non integer value, how can I get it to loop properly?
所以我试图让我的二次方程解代码循环,除非输入"0"作为二次系数中的任何 1。 它工作正常,直到输入非整数值,程序在其中终止。 我希望代码吐出一条消息,提示用户输入数值,并正常继续循环。
#include <iostream>
#include <cmath>
using namespace std;
int main() {
for ( ; ; ){
float a, b, c, D, x1, x2, real, im;
cout << "Please enter the Quadratic Coefficients" << endl;
cin >> a >> b >> c;
if (cin.fail()){
cout << "Error, please enter numerical values!" << endl;
cin >> a >> b >> c;
}
if ((a == 0) || (b == 0) || (c == 0)){
break;
}
D = b*b - 4*a*c;
if (D < 0) {
real = -b/(2*a);
im = sqrt(-D)/(2*a);
cout << "Roots are Complex" << endl;
cout << "x1 = " << real << "+" << im << "i" << endl;
cout << "x2 = " << real << "-" << im << "i" << endl;
}
else if (D == 0) {
x1 = (-b + sqrt(D)) / (2*a);
cout << "Real and Repeated Roots" << endl;
cout << "x1 = " << x1 << endl;
}
else if (D > 0)
{
x1 = (-b + sqrt(D)) / (2*a);
x2 = (-b - sqrt(D)) / (2*a);
cout << "Real and Distinct Roots" << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
} }
return 0;
}
这里的这个解决方案应该会有所帮助。
cin.fail()
将输入流设置为失败状态,您需要手动重置它以使其执行任何进一步的工作。当您再次调用cin
时,它会注意到其失败状态并继续,否则。
cin >> a >> b >> c;
if (cin.fail()){
cin.clear(); //removes error flags
cin.ignore(); //ignores last input
cout << "Error, please enter numerical values!" << endl;
cin >> a >> b >> c;
}
相关文章:
- while 循环不以哨兵值终止
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- C++ 即使不满足条件,循环也会终止
- 为什么 EOF 在循环扫描期间没有终止?
- 对于检查 >=0 终止条件时的循环索引类型
- 程序在终止循环后不接收输入
- 即使我尝试递减 t,While 循环也没有终止
- 如何修复不会在退出选择时终止的 do-while 循环
- 如何用字符终止整数输入循环?
- 读入变量时循环终止,'Range_error' on C++
- 当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?
- 如何正确终止此循环?
- 多个查询的循环过早终止
- 循环终止不正确时
- c 在函数的循环终止时
- 而循环终止问题
- 当循环终止被覆盖时
- 循环终止条件错误的 cpp 向量
- C++作业(循环终止时)
- 是否定义有一个随机的循环终止条件?