【问题标题】:Where is the problem in my struct declaration?我的结构声明中的问题在哪里?
【发布时间】: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应该做什么?您有两个无效的复合文字,并且您不会从该函数返回任何内容,正如您的编译器应该告诉您的那样。

标签: c struct


【解决方案1】:

整个函数不会做任何在该函数之外可见的事情:

complex result(complex n1, complex n2) {
    (complex){.real = n1.real + n2.real};
    (complex){.imag = n1.imag + n2.imag};
}

首先,您不返回任何值。您的编译器应该对此显示警告。 然后你有 2 个你不使用的复合文字。您不会将其分配给任何东西或将其归还。 编译器也可能对此发出警告。

您的代码基本上只是被编译器完全删除的{0+1; 1+2;}

你可能想做的是:

complex result(complex n1, complex n2) {
  complex res = {.real = n1.real + n2.real,
                 .imag = n1.imag + n2.imag };
  return res;
}

complex result(complex n1, complex n2) {
  return (complex){.real = n1.real + n2.real,
                   .imag = n1.imag + n2.imag };
}

【讨论】:

  • 哦,非常感谢!
  • @NewbieBoy 如果有帮助,您可以接受答案。