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

C语言实现两个复数相除结果始终为0+0i的问题排查

问题核心原因
  • 数据类型选择错误:你定义的complex结构体实部、虚部均为int整数类型,而复数除法的结果几乎都是浮点值,C语言中整数除法会直接舍弃小数部分,只要分子绝对值小于分母,运算结果就会被截断为0,这是你得到0+0i的根本原因。
  • 输入输出格式符存在适配隐患:修改为浮点类型后,对应的scanf、printf格式符也需要同步调整。
  • 你的复数除法有理化计算公式逻辑是正确的,main函数的输入调用逻辑也没有问题。
修复后的完整代码
#include <stdio.h>

// 将结构体成员改为double类型支持浮点数存储
typedef struct complex {
    double real;
    double imag;
} complex;

complex divide(complex n1, complex n2);

int main() {
    complex n1, n2, rez;

    printf("real part n1: ");
    scanf("%lf", &n1.real);
    printf("imag part n1: ");
    scanf("%lf", &n1.imag);

    printf("real part n2: ");
    scanf("%lf", &n2.real);
    printf("imag part n2: ");
    scanf("%lf", &n2.imag);

    rez = divide(n1, n2);
    // 调整输出格式符,保留两位小数更易读
    printf("Result= %.2lf+%.2lfi", rez.real, rez.imag);
    return 0;
}

complex divide(complex n1, complex n2)
{
    complex rez;
    double denominator = n2.real * n2.real + n2.imag * n2.imag;
    // 计算公式保持不变,现在是浮点数除法不会截断
    rez.real = (n1.real * n2.real + n1.imag * n2.imag) / denominator;
    rez.imag = (n1.imag * n2.real - n1.real * n2.imag) / denominator;
    return rez;
}
测试说明

比如输入n1为1+2i,n2为3+4i,运行后输出结果为0.44+0.08i,和数学计算结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:36:03