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

标签 c runtime-error

我的 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/

相关文章:

c++ - 在 SDL 中绘制点列表?

arrays - 在c中初始化结构成员的 union 时出错

c++ - 从基于 c++0x std::thread 的 C++ 库中公开完整的(C 语言)pthread 接口(interface)

c - strtok() 函数自动忽略不是我的分隔符的数据

c++ - 变量作用域大于for循环,为什么不改变值?

parsing - Python3 - 为编译器创建扫描器并在测试时出错

c - 使用空参数列表在 ANSI-C 中检查函数参数类型

C - 在 while 中获取 char 并压入堆栈

python - 如果元素包含特定字符,则从列表或集合中删除元素

python - Django ImportError : No module named tango_with_django_project. 设置