求方程 的根,用三个函数分别求当b^2-4ac大于0、等于0、和小于0时的根,并输出结果。从主函数输入a、b、c的值。
输入格式
a b c
输出格式
x1=? x2=?
样例输入
复制
4 1 1
样例输出
复制
x1=-0.125+0.484i x2=-0.125-0.484i
//注意输出格式就好了,拿x1举例:cout<<"x1="<<-b/(2.0*a)<<"+"<<sqrt(-d)/(2.0*a)<<"i ";
这里的除数最好是用2.0,告诉程序要保留小数,d指的是德尔塔(b^2-4ac)
//为了保留3为小数,用iomanip头文件里的fixed<<setprecision(3)<<...告诉程序保留几位(3),详情见代码!--------------------------》
//求方程的根
#include<iostream>
#include<iomanip>
#include<cmath> //网站自带的sqrt的头文件 开根号
using namespace std;
/*德尔塔 > 0*/
int Fun1(int a, int b, int c) {
float d = b * b - 4 * a * c;
float x1 = (-b + sqrt(d)) / (2.0 * a);
float x2 = (-b - sqrt(d)) / (2.0 * a);
//正常两根直接输出
cout << "x1=" << x1 << " " << "x2=" << x2;
return 0;
}
/*德尔塔 < 0*/
int Fun2(int a, int b, int c) {
float d = b * b - 4 * a * c;/*(2.0*a)*/
cout << "x1=" << fixed << setprecision(3) << -b / (2.0 * a) << "+" << fixed << setprecision(3) << sqrt(-d) / (2.0 * a) << "i ";
cout << "x2=" << fixed << setprecision(3) << -b / (2.0 * a) << "-" << fixed << setprecision(3) << sqrt(-d) / (2.0 * a) << "i ";
return 0;
}
/*德尔塔==0*/
int Fun3(int a, int b, int c) {
float d = b * b - 4 * a * c;
float x = (-b + sqrt(d)) / (2.0 * a);
cout << "x1=" <<fixed<<setprecision(3)<< x << " x2=" <<fixed<<setprecision(3)<< x;
return 0;
}
int main() {
int a, b, c;
cin >> a >> b >> c;
if (b * b - 4 * a * c > 0) {
Fun1(a, b, c);
}
else if (b * b - 4 * a * c < 0) {
Fun2(a, b, c);
}
else {
Fun3(a, b, c);
}
return 0;
}