gpt4 book ai didi

c - 无法找到二次方程代码中的错误

转载 作者:行者123 更新时间:2023-11-30 21:03:40 24 4
gpt4 key购买 nike

我的 friend 要求找出其中的错误,我得到的复杂解决方案的实部为零。谁能告诉我原因以及如何解决感谢您的帮助

#include<stdio.h>
#include<math.h>
main()
{
int i,a,b,c,d;
float x,y;
printf("ener the values for a,b,c");
scanf("%d%d%d",&a,&b,&c);
if(a==0)
{
printf("not a quadratc equation");
}
else
{
d=(b*b-4*a*c);
if(d==0)
{
printf("roots are equal");
x=-b/(2*a);
printf("\n%f\n%f",x,x);
}
else if(d>0)
{
x=(-b+sqrt(d))/(2*a);
y=(-b-sqrt(d))/(2*a);
printf("the roots are %f and %f",x,y);
}
else if(d<0)
{
x=-(b/(2*a));
printf("%f",x);
y=(sqrt(-d))/(2*a);
printf("the roots are %f+i%f and %f-i%f",x,y,x,y);
}
}
}

最佳答案

您正在对 int 变量执行大量数学运算,并将结果存储在 float 中。这并不意味着算术是使用 float 执行的,它都是整数。

sqrt() function返回double,这样就保存了虚部。对于实部,所有数学运算都是整数,因此 -(b/(2 * a)) 将使用整数进行计算,然后最终结果将存储在 x 作为 float ,当然没有任何小数部分。

关于c - 无法找到二次方程代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23538230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com