2

计算一元二次方程的解_wx63512a03a0f63的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_15838996/5951505
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

以下为题目

从键盘输入a, b, c的值,编程计算并输出一元二次方程ax2 + bx + c = 0的根,当a = 0时,输出“Not quadratic equation”,当a ≠ 0时,根据△ = b2 -4*a*c的三种情况计算并输出方程的根。

输入描述:

多组输入,一行,包含三个浮点数a, b, c,以一个空格分隔,表示一元二次方程ax2 + bx + c = 0的系数。

输出描述:

针对每组输入,输出一行,输出一元二次方程ax2 + bx +c = 0的根的情况。

  如果a = 0,输出“Not quadratic equation”;

  如果a ≠  0,分三种情况:

△ = 0,则两个实根相等,输出形式为:x1=x2=...

△  > 0,则两个实根不等,输出形式为:x1=...;x2=...,其中x1  <=  x2。

△  < 0,则有两个虚根,则输出:x1=实部-虚部i;x2=实部+虚部i,即x1的虚部系数小于等于x2的虚部系数,实部为0时不可省略。实部= -b / (2*a),虚部= sqrt(-△ ) / (2*a)

所有实数部分要求精确到小数点后2位,数字、符号之间没有空格。

题目来自与牛客BC73题

#include<stdio.h>
#include<math.h>
int main()
{
double a,b,c,d,x1,x2;//以下代码中2*a必须打括号否则答案会出现错误
while(scanf("%lf %lf %lf",&a,&b,&c)!=EOF)//这里的代码是为了满足题目中所说的多组输入而写的
{
if(a==0)
{
printf("Not quadratic equation");
}
else
{
d=b*b-(4*a*c);
if(d==0)
{
x1=-b/(2*a);
x2=x1;
if(x1==0)
{
x1=0;
x2=0;
}
printf("x1=x2=%.2lf",x1);
}
else if(d>0)
{
x1=(-b+sqrt(d))/(2*a);x2=(-b-sqrt(d))/(2*a);//
if(x1>x2)
{
double t=x1;
x1=x2;
x2=t;
}
if(x1==-0)
{
x1=0;
}
if(x2==-0)
{
x2=0;
}
printf("x1=%.2lf;x2=%.2lf",x1,x2);
}
else
{
double s,x;
s=-b/(2*a);x=sqrt(-d)/(2*a);
if(s==0)
{
s=0;
}
printf("x1=%.2lf-%.2lfi;x2=%.2lf+%.2lfi",s,x,s,x);
}
}
printf("\n");//这里是为了完成每一次计算结果后换行。
}
return 0;
}

运算结果如图

计算一元二次方程的解_浮点数

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK