原题来自菜鸟教程
C++ 实例 - 求一元二次方程的根
实现方法相当简单 就是最基础的C语言程序
以下是菜鸟教程给的答案——
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
cout << "输入 a, b 和 c: ";
cin >> a >> b >> c;
discriminant = b*b - 4*a*c;
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (discriminant == 0) {
cout << "实根相同:" << endl;
x1 = (-b + sqrt(discriminant)) / (2*a);
cout << "x1 = x2 =" << x1 << endl;
}
else {
realPart = -b/(2*a);
imaginaryPart =sqrt(-discriminant)/(2*a);
cout << "实根不同:" << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}
return 0;
}
嗯 自己也很快就实现了这个功能
但是在进行测试的时候
啊三种情况好烦啊 还得一遍遍地编译运行(明明这样更快啊喂!
有没有啥方法可以一遍试完这三种情况呢。
加个计数器吧
嗯 perfect~
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int count,counta,countb,countc;
float det,x1,x2,a,b,c;
float realPart,imaginaryPart;
while(count != 1){
cout << "please input the parameter:" << endl;
cin >> a >> b >> c;
det = b*b - 4*a*c;
if(det > 0){
cout << "the roots are real and different" << endl;
x1 = (-b + sqrt(det))/(2*a);
x2 = (-b - sqrt(det))/(2*a);
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
counta = 1;
}
else if(det == 0){
cout << "the root is equal" << endl;
x1 = x2 = -b/(2*a);
cout << "x1 = x2 = "<< x1 << endl;
countb = 1;
}
// det<0 两个根是复数(跟高中讲的不太一样嗷) 两个复数根为共轭复根
else {
cout << "一对共轭复根出现辽" << endl;
realPart = -b/(2*a);
imaginaryPart = ( -sqrt(det) ) / (2*a);
if (imaginaryPart){
// 复数中的b不存在的情况
cout << "x1 = " << realPart << endl;
cout << "x2 = " << realPart << endl;
countc = 1;
}
else{
cout << "x1 = " << realPart << '+' << imaginaryPart << 'i' << endl;
cout << "x2 = " << realPart << '-' << imaginaryPart << 'i' << endl;
countc = 1;//计数器
}
}
if(counta==1 && countb==1 && countc==1){
count = 1;
}
}
cout << "duang----------------------------------duang" << endl;
cout << "已经试过了det>0 det=0 det<0 三种情况咯~" << endl;
}
终于可以愉快地一遍测试完成了呢。。
(工作量貌似增加了的亚子