使用结构的复数加法

标签 c struct dev-c++ complex-numbers

为什么这段代码在 Dev-CPP 上执行完美,但在 Borland Turbo C 上执行失败?

在 Turbo C 中执行时显示 Input real part: Stack Overflow !

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct complex
{
 int real;
 int img;
};

typedef struct complex com;
com read(com);
com add(com,com);
void show(com);

void main()
{
 com c1,c2,c3;
 clrscr();
 c1=read(c1);
 c2=read(c2);
 c3=add(c1,c2);
 show(c3);
 getch();
}

com read(com c)
{
 printf("Input real part: ");
 scanf("%d",&c.real);
 printf("Input imaginary part: ");
 scanf("%d",&c.img);
 return (c);
}

void show(com c)
{
 printf("%d+%di",c.real,c.img);
}

com add(com c1,com c2)
{
 com c3;
 c3.img=c1.img+c2.img;
 c3.real=c1.real+c2.real;
 return (c3);
}

最佳答案

无需按值传递结构成员。 可以执行以下操作:

#include<stdio.h>
#include<stdlib.h>

struct complex
{
  int real;
  int img;
};

typedef struct complex com;
void read(com *);
void add(com,com, com *);
void show(com);

int main()
{
  com c1,c2,c3;
  read(&c1);
  read(&c2);
  add(c1,c2, &c3);
  show(c3);
  return 0;
}

void read(com *c)
{
  printf("Input real part: ");
  scanf("%d",&c->real);
  printf("Input imaginary part: ");
  scanf("%d",&c->img);
}

void show(com c)
{
  printf("%d+%di",c.real,c.img);
}

void add(com c1,com c2, com *c3)
{
  c3->img=c1.img+c2.img;
  c3->real=c1.real+c2.real;
}

关于使用结构的复数加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828703/

相关文章:

c - 没有这样的文件或目录,但文件在那里

c - 使用 strtok 和填充数组

c - 从文件中读取并在动态结构上传输

c - 使用链表时从不兼容的指针类型赋值

c - EOF 在...EOF 之前到达

c - 内存分配问题?

c - 如何解释 C 中结构的成员访问(点)运算符?

c++ - "cannot open output file filename.exe: Permission denied"

c - scanf 不扫描 %c 字符而是跳过该语句,这是为什么?

c - 将存储为链表的两个数字相加 - 无法使用 C 解决