当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?

My Quadratic equation code terminates when I enter a non integer value, how can I get it to loop properly?

本文关键字:循环 终止 二次方程 输入 整数 我的 代码      更新时间:2023-10-16

所以我试图让我的二次方程解代码循环,除非输入"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;
}