使用结构添加复数

时间:2012-03-22 18:56:02

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

1 个答案:

答案 0 :(得分:1)

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

#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;
}