逻辑概念:
一元二次方程的格式为:ax²+bx+c=0(a≠0)
求根公式为:Δ = b²-4×a×c
这个程序需要用到头文件#include <>当中的sqrt()函数。
sqrt()函数用于计算一个非负实数的平方根(即开根号)。
代码示例:
-
#include <>
-
#include <>
-
int main()
-
{
-
float a,b,c,q;
-
float x1,x2;
-
printf("Please enter the a:");
-
scanf("%f",&a);
-
printf("Please enter the b:");
-
scanf("%f",&b);
-
printf("Please enter the c:");
-
scanf("%f",&c);
-
q = b*b - 4*a*c;
-
x1 = (-b+sqrt(q)) / (2*a);
-
x2 = (-b-sqrt(q)) / (2*a);
-
printf("\n方程为%.1fx²+%.1fx+%.1f=0\n",a,b,c);
-
if(q < 0)
-
printf("∵ Δ < 0\n∴ 方程无解\n");
-
else if(q == 0)
-
printf("∵ Δ = 0\n∴ x1=x2=%.2f",x1);
-
else
-
printf("∵ Δ = %.2f\n开根号得%.2f\n∴ x1=%.2f\nx2=%.2f\n",q,sqrt(q),x1,x2);
-
return 0;
-
}
输入示例:
-
Please enter the a:5
-
Please enter the b:7
-
Please enter the c:2
输出示例:
-
Please enter the a:5
-
Please enter the b:7
-
Please enter the c:2
-
-
方程为5.0x²+7.0x+2.0=0
-
∵ Δ = 9.00
-
开根号得3.00
-
∴ x1=-0.40
-
x2=-1.00