你根本想不到会有这种错误的出现
我是在做谭老出版的c语言课后习题中做到的这题。
题目为:
求方程ax2+bx+c=0ax^{2}+bx+c=0ax2+bx+c=0的根,用3个函数分别求当:b2−4acb^{2}-4acb2−4ac大于0、等于0、小于0时的根并输出结果。从主函数中输入a,b,ca,b,ca,b,c的值。
废话少说,直接上代码
#include<stdio.h>
#include<math.h>
float sqrtda(float d,float a,float b)
{
float x1,x2;
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("该函数有两个不相等的实根:%.1f %.1f",x1,x2);
}
float sqrtdeng(float d,float a,float b)
{
float x;
x=-b/(2*a);
printf("该函数有两个相等的实根:%.1f",x);
}
float sqrtxiao(float d,float a,float b)
{
float x1,x2;
x1=-b/(2*a);
x2=sqrt(d/(4*a*a));
printf("该函数有两个不相等的共轭复根:%.1f+%.1fi %.1f-%.1fi",x1,x2,x1,x2);
}
int main()
{
float sqrtda(float d,float a,float b);
float sqrtdeng(float d,float a,float b);
float sqrtxiao(float d,float a,float b);
float a,b,c,d;
scanf("请输入三个系数:%f %f %f",&a,&b,&c);
printf("要求的函数为: %.0fx*x + %.0fx + %.0f\n",a,b,c);
d=b*b-4*a*c;
if (d>0)
{
sqrtda(d,a,b);
}
else if (d==0)
{
sqrtdeng(d,a,b);
}
else
{
sqrtxiao(d,a,b);
}
return 0;
}
我的错误不止一处,先看第一处错误。

发现没有,我输入了正确的a,b,ca,b,ca,b,c,但是显示出来的a,b,ca,b,ca,b,c却不对。

细心的小伙伴可能发现了。
问题出现在了这里
scanf("请输入三个系数:%f %f %f",&a,&b,&c);
我本来是想使代码更人性化一点,但就是这一点,导致我花了一个小时才找出这个bug。
scanf的输入具有严格的标准,我写的括号里包含了请输入三个系数:,所以在输入的时候必须带有这一行话。
下面看我修改的
printf("请输入三个系数:");
scanf("%f %f %f",&a,&b,&c);

然而这个问题解决了,其他地方还有bug。
细心的小伙伴可能又发现了。
问题出在这里
float sqrtxiao(float d,float a,float b)
{
float x1,x2;
x1=-b/(2*a);
x2=sqrt(d/(4*a*a));
printf("该函数有两个不相等的共轭复根:%.1f+%.1fi %.1f-%.1fi",x1,x2,x1,x2);
}

可以看到,共轭复根的输出中有==-1.#INDOO==的出现。
而经过我的查询,这是浮点数编程常见的错误输出。
-1.#IND / nan:一般来说,它们来自于任何未定义结果(非法)的浮点数运算。"IND"是 indeterminate 的缩写,而"nan"是 not a number 的缩写。产生这个值的常见例子有:对负数开平方根,对负数取对数,0.0/0.0,0.0*∞, ∞/∞ 等。
而本题的错误就在于d已经算出来小于0了,但是我仍然开了平方根。
解决了这些问题,我终于把程序调试好了,下面把正确代码发出来:
#include<stdio.h>
#include<math.h>
float sqrtda(float d,float a,float b)
{
float x1,x2;
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("该函数有两个不相等的实根:%f %f",x1,x2);
}
float sqrtdeng(float d,float a,float b)
{
float x;
x=-b/(2*a);
printf("该函数有两个相等的实根:%f",x);
}
float sqrtxiao(float d,float a,float b)
{
float x1,x2;
x1=-b/(2*a);
x2=sqrt(-d/(4*a*a));
printf("该函数有两个不相等的共轭复根:%.1f+%.1fi %.1f-%.1fi",x1,x2,x1,x2);
}
int main()
{
float sqrtda(float d,float a,float b);
float sqrtdeng(float d,float a,float b);
float sqrtxiao(float d,float a,float b);
float a,b,c,d;
printf("请输入三个系数:");
scanf("%f %f %f",&a,&b,&c);
printf("要求的函数为: %.0fx*x+%.0fx+%.0f\n",a,b,c);
d=b*b-4*a*c;
if (d>0)
{
sqrtda(d,a,b);
}
else if (d==0)
{
sqrtdeng(d,a,b);
}
else
{
sqrtxiao(d,a,b);
}
return 0;
}

代码之路很长,愿诸君皆能笑到最后!
作者分享了解决谭老C语言课后习题中关于一元二次方程根的求解程序中的错误,涉及浮点数运算和条件判断。通过实例展示了如何调试代码,正确处理实根、复根和特殊情况。
717

被折叠的 条评论
为什么被折叠?



