C语言程序设计-谭浩强

例4.1

在例3.5的基础上对程序进行改进 题目要求解得ax2+bx+c=0方程的根。由键盘输入a,b,c。假设a,b,c的值任意,并不保b2-4ac≥0 需要在程序中进行判别,如果b2-4c≥0,就输出两个实根,

如果b2-4ac<0,则输出无解;

公式法

#include<stdio.h>
#include<math.h> //调用sqrt函数 sqrt函数开方函数
int main()
{
double a, b, c, test, x1, x2; //test是平方根判别公式
scanf("%lf%lf%lf", &a, &b, &c);
test = b*b - 4 * a*c;
if (test < 0)
{
printf("无解\n");
}
else
{
x1 = (-b + sqrt(test)) / (2.0*a);
x2 = (-b - sqrt(test)) / (2.0*a); //公式法解题
}

printf("x1=%f\nx2=%f", x1, x2);
return 0;
}

猜你喜欢

转载自www.cnblogs.com/old-horse/p/12468723.html