所以我试图让我的二次方程解决方案代码循环,除非" 0"输入为任何一个二次系数。 它工作正常,直到输入程序终止的非整数值。 我希望代码吐出一条消息,提示用户输入数值,并继续正常循环。
#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;
}
答案 0 :(得分:0)
This solution here should help。
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;
}