入门级求根
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float a,b,c,d;
cout<<"输入三个系数";
cin>>a>>b>>c;
cout<<"a="<<a<<'\t'<<"b="<<b<<'\t'<<"c="<<c<<endl;
d=b*b-4*a*c;
if (d<0)
{
cout<<"该方程无实根!"<<endl;
}
else{
d=sqrt(d);
if(d)
{
cout<<"该方程有两个不等的实数根"<<endl;
cout<<"x1="<<(-b+d)/2/a<<'\t'<<"x2="<<(-b-d)/2/a<<endl;
}
else{cout<<"该方程有两个相等的根"<<endl;
cout<<"x1=x2="<<(-b+d)/2/a<<endl;}
}
return 0;
}
该方法无法求出虚根(无法求出的d<0时的虚根);下面用调用函数的方法求一元二次方程的根
先补充一个知识点:
例题如下:设置精度的操作
图片来源:C语言程序设计教程(第三版)课后习题4.9 (C++代码)-Dotcpp编程社区
#include<iostream>
#include<cmath>
#include <iomanip>
using namespace std;
void fun1(float a, float b, float d) //d>0时,直接带公式
{
float x1,x2;
d = sqrt(d);
x1 = (-b + d) / 2 / a;
x2 = (-b - d) / 2 / a;
cout << "x1= "<<x1 <<'\t' << "x2="<<x2;
}
void fun2(float a, float b) //d=0时,直接带公式
{
float x;
x = -b / 2 / a;
cout<<"x1=x2="<< x;
}
void fun3(float a, float b,float d) //d<0时,用虚数表示方程的根
{
d = -d;
d = sqrt(d);
d = d / 2 / a;
float x = -b / 2 / a;
cout << fixed << setprecision(3) << "x1=" << x << "+" << d << "i" << '\t' << "x2=" << x << "-" << d << "i";
}
int main()
{
float a, b,c,d;
cin >> a >> b>>c;
d = b * b - 4*a*c;
if (d > 0)
fun1(a, b, d);
else if (d == 0) //易错写成=
fun2(a, b);
else
fun3(a, b, d);
return 0;
}