c - 如何使用结构来表示复数

标签 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;
}

最佳答案

你的代码毫无意义:

  • 您正在定义两个相同的结构,这似乎毫无意义。
  • 结构包含指向 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/

相关文章:

c - 简单链接列表 (FILO) 不起作用

c - 通过 C 中的直线位操作查找正整数的最高有效位或以 2 为底的对数

c - 结构体数组的动态值?

c# - 将具有随机唯一数字的数组转换为具有连续数字的数组?

c - 分配和获取 union 值,类型双关

c - 如何从 unix gettime Jan 1970 API 推断当前时间(时钟)?

c - 为什么此代码打印 "False",尽管 int 的大小大于 -1?

c - 如果 'a' 在 C 中是一个整数数组,为什么 'a + 1' 和 '&a + 1' 不同?

c - 虚拟内存系统、页表和TLB

c - 为什么我不能输入带空格的字符串?