题目:对于一元二次方程a+bx+c=0,判断有无实根,若有,则输出实根。(a,b,c由键盘输入)。
分析:1、键盘键入a、b、c;
2、求delta = - 4ac的值;
3、判断与0的大小关系。若delta>0,则有两个不同的实根,带入求根公式,得到实根为x1 = ,x2 = ;若delta=0,则有两个相同的实根,则根为x1 = x2 = ;若delta<0,则无实根;
代码:
# include <stdio.h>
# include <math.h>
int main(void)
{
double a, b, c;
double delta;
double x1, x2;
char ch;
do
{
printf("请输入一元二次方程的三个系数:\n");
printf("a = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
delta = b*b - 4*a*c;
if (delta > 0)
{
x1 = (-b + sqrt(delta)) / (2*a);
x2 = (-b - sqrt(delta)) / (2*a);
printf("有两个解,x1 = %lf, x2 = %lf\n", x1, x2);
}
else if (0 == delta)
{
x1 = x2 = (-b) / (2*a);
printf("有唯一解,x1 = x2 = %lf\n", x1, x2);
}
else
{
printf("无实数解!\n");
}
printf("您想继续么(Y/N): ");
scanf(" %c", &ch); //%c前面必须得加一个空格 原因略
} while ('y'==ch || 'Y'==ch);
return 0;
}
3、输出结果:
请输入一元二次方程的三个系数:
a = 1
b = 2
c = 3
无实数解!
您想继续么(Y/N): y
请输入一元二次方程的三个系数:
a = 2
b = 3
c = 1
有两个解,x1 = -0.500000, x2 = -1.000000
您想继续么(Y/N): n
...Program finished with exit code 0
Press ENTER to exit console.