C++中求一个一元二次方程的根
输入的是三个系数,让你求解… …
代码如下:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
double a,b,c,d,e,f,g;
cin>>a>>b>>c;
f=b*b-4*a*c;
g=sqrt(f);
if(f<0){
cout<<"N"<<"o"<<" "<<"answer"<<"!";
}
else if(f==0){
d=-2*a/b;
cout<<d;
}
else{
c=(-b+g)/(2*a);
d=(-b-g)/(2*a);
cout<<c<<endl<<d;
}
return 0;
} 展开
我是用C语言写的,已经AC了,你看看吧
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define EPSION 0.000001
int main(void)
{
double a = 0.0, b = 0.0, c = 0.0;
double sqrtVal = 0.0;
double answerOne = 0.0, answerSecond = 0.0;
scanf("%lf%lf%lf", &a, &b, &c);
sqrtVal = b * b - 4 * a * c;
if(sqrtVal < 0.0)
{
printf("No answer!");
}
else if(fabs(sqrtVal - 0.0) > EPSION)
{
answerOne = (-1.0 * b - sqrt(sqrtVal)) / (2 * a);
answerSecond = (-1.0 * b + sqrt(sqrtVal)) / (2 * a);
printf("%.2lf\n%.2f", answerOne, answerSecond);
}
else
{
answerOne = (-1.0 * b - sqrt(sqrtVal)) / (2 * a);
printf("%.2lf\n", answerOne);
}
return 0;
}
好多人都在用苏州… …
啥苏州啊?听不懂。。。。-_-!!
我试了一下,果断AC
#include<iostream>
#include <iomanip>
#include<math.h>
using namespace std;
int main()
{
double a,b,c,d,e,f,g;
cin>>a>>b>>c;
f=b*b-4*a*c;
if(f<-1e-6){
cout<<"No answer!"<<endl;
}
else if(fabs(f)<=1e-6){
d=-2*a/b;
cout<<fixed<<setprecision(2)<<d<<endl;
}
else{
g=sqrt(f);
c=(-b+g)/(2*a);
d=(-b-g)/(2*a);
cout<< fixed<<setprecision(2)<<c<<endl<<setprecision(2)<<d<<endl;
}
return 0;
}
#include 是什么… …
fixed<<setprecision(2)
输出对齐,要引进那个头文件