【发布时间】:2025-04-04 17:15:01
【问题描述】:
这是我关于对 2 个复数求和的代码。
#include <stdio.h>
typedef struct complex {
float real;
float imag;
} complex;
complex result(complex n1, complex n2);
int main() {
complex n1, n2;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
printf("Sum = %.1f + %.1fi", result(n1,n2).real, result(n1,n2).imag);
return 0;
}
complex result(complex n1, complex n2) {
(complex){.real = n1.real + n2.real};
(complex){.imag = n1.imag + n2.imag};
}
这是输出:
For 1st complex number
Enter the real and imaginary parts: 1
1
For 2nd complex number Enter the real and imaginary parts: 1
1
Sum = 0.0 + 2.0i
我不明白为什么只从 n1 和 n2 传递结果的 .imag 部分。
【问题讨论】:
-
您是否尝试通过调试器运行您的代码?
-
那个函数
result应该做什么?您有两个无效的复合文字,并且您不会从该函数返回任何内容,正如您的编译器应该告诉您的那样。