如何使用结构来表示复数

non*_*one 0 c

我需要编写一个程序,它使用结构来定义复数,即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;
}
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 7

你的代码没什么意义:

  • 你定义了两个相同的结构,这似乎毫无意义.
  • 这些结构包含指向浮点数的指针,而不是实际的浮点数,这似乎是不明智的.
  • 使用浮点数读取的代码scanf()使用非初始化指针来存储值,这会导致未定义的行为.
  • 您不应该使用%d格式说明符来读取浮点数,它是整数.

尝试:

typedef struct {
  float real;
  float imaginary;
} complex;

complex a, b;

scanf("%f", &a.real);
scanf("%f", &a.imaginary);
Run Code Online (Sandbox Code Playgroud)