You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中打印二次方程虚根?代码运行虚根显示0.00000i求排查

问题原因

你代码里的错误主要有3处:

  • 对负数直接调用sqrt()会返回NaN,且你定义的xr、ximg1、ximg2都是普通double类型而非复数类型,调用cimagf()获取普通实数的虚部本身就会返回0,这是虚根输出0的核心原因。
  • 求根公式的运算优先级写错:/ 2 * a等价于「先除以2再乘a」,和求根公式要求的「除以2a」完全不符,所有计算根的行都存在这个错误。
  • 判别式小于0时,虚部的大小应该对disc取绝对值后再开平方,不能直接对负数开平方。

修正方案

你现在是手动拆分实部和虚部的数值,不需要调用crealf、cimagf这类复数操作函数,直接打印计算得到的数值即可,修正后的完整代码如下:

//C program to find the root of the quadratic equation
#include <stdio.h>
#include <math.h>
#include <complex.h>

int main()
{
    double  a, b, c, x, x1, x2, disc, xr, ximg;
    
    printf("Please enter the value of quadratic equation, a: ");
    scanf("%lf", &a);
    printf("Please enter the value of quadratic equation, b: ");
    scanf("%lf", &b);
    printf("Please enter the value of quadratic equation, c: ");
    scanf("%lf", &c);

    if( a == 0 )
    {
        x = -(c/b);
        printf("\nThis is not a quadratic equation.\n");
        printf("x = %.3lf", x);
    }
    else{
    disc = (b*b) - 4*a*c;
        if( disc == 0 ){
             x1 = -b / (2 * a);
             x2 = x1;
             printf("x1 = %lf, x2 = %lf", x1, x2);
        }
        else if(disc > 0){
            x1 = ( -b + sqrt( disc ) ) / (2 * a);
            x2 = ( -b - sqrt( disc ) ) / (2 * a);
            printf("x1 = %.1lf, x2 = %.1lf", x1, x2);
        }
        else{
            ximg = sqrt( -disc ) / (2 * a);
            xr = - b / ( 2 * a );
            printf("x1 = %lf + %lfi, x2 = %lf - %lfi", xr, ximg, xr, ximg);
        }
    }

    return 0;
}

测试效果

输入你给出的测试用例a=4、b=1、c=3,输出结果为:

x1 = -0.125000 + 0.861987i, x2 = -0.125000 - 0.861987i

内容的提问来源于stack exchange,提问作者HOCK WENG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:36:05