我需要编写一个程序,使用结构来定义复数,即 z1 = x + yi。然后添加 2 个复数。在继续我的代码之前,我需要弄清楚如何正确初始化它们。到目前为止,我已经尝试了一些东西,这是我想出的最好的,但它仍然没有编译。
这是我的代码的副本,我只需要修复这部分,然后我就可以自己完成其余部分。
#include<stdio.h>
typedef struct complex1{
float *real1;
float *imaginary1;
} complex1;
typedef struct complex2{
float *real2;
float *imaginary2;
} complex2;
int main(){
struct complex1 real;
struct complex1 *realptr;
struct complex1 imaginary;
struct complex1 *imaginaryptr;
struct complex2 real;
struct complex2 *realptr;
struct complex2 imaginary;
struct complex2 *imaginaryptr;
printf("Please enter variable x1.");
scanf("%d", &real.real1);
printf("Please enter variable y1.");
scanf("%d", &imaginary.imaginary1);
printf("Please enter variable x2.");
scanf("%d", &real.real2);
printf("Please enter variable y2.");
scanf("%d", &imaginary.imaginary2);
printf("You have entered: %d,%d,%d,%d\n",
real.real1, imaginary.imaginary1,real.real2, imaginary.imagnary2);
return 0;
}
最佳答案
你的代码毫无意义:
- 您正在定义两个相同的结构,这似乎毫无意义。
- 结构包含指向 float 的指针,而不是实际的 float ,这似乎是不明智的。
- 您使用
scanf()
读取 float 的代码正在使用未初始化的指针来存储值,这会导致未定义的行为。 - 您不应使用
%d
格式说明符来读取 float ,它适用于整数。
尝试:
typedef struct {
float real;
float imaginary;
} complex;
complex a, b;
scanf("%f", &a.real);
scanf("%f", &a.imaginary);
关于c - 如何使用结构来表示复数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5093566/