-1

我需要编写一个函数来读取用户的输入并将其存储到结构中。在c。

typedef struct {
   float real, imag;
} complex_t;


complex_t read_complex(void)
{

}

我应该如何扫描输入?

4

2 回答 2

0
#include < stdio.h >

typedef struct
{
  int re;// real part  
  int im;//imaginary part
} complex;

void add(complex a, complex b, complex * c)
{
  c->re = a.re + b.re;
  c->im = a.im + b.im;
}

void multiply(complex a, complex b, complex * c)
{
  c->re = a.re * b.re - a.im * b.im;
  c->im = a.re * b.im + a.im * b.re;
}

main()
{
  complex x, y, z;
  char Opr[2];

  printf("  Input first operand. \n");
  scanf("%d %d", &x.re, &x.im);
  printf("  Input second operand. \n");
  scanf("%d %d", &y.re, &y.im);
  printf("  Select operator.(+/x) \n");
  scanf("%1s", Opr);

  switch(Opr[0]){
    case '+':
          add(x, y, &z); 
          break;
    case 'x':
          multiply(x, y, &z);
          break;
    default:
      printf("Bad operator selection.\n");
      break;
  }
  printf("[%d + (%d)i]", x.re,x.im);
  printf(" %s ", Opr);
  printf("[%d + (%d)i] = ", y.re, y.im);
  printf("%d +(%d)i\n", z.re, z.im);
}
于 2012-11-19T18:44:19.547 回答
0

你可以轻松做到。正如您提到的函数签名,您应该尝试以下操作:

complex_t read_complex(void)
{
    complex_t c;
    float a,b;
    printf("Enter real and imaginary values of complex :");
    scanf("%f",&a);
    scanf("%f",&b);
    c.real=a;
    c.imag=b;
    return c;
}

int main()
{
complex_t cobj;
cobj=read_complex(void);
printf("real  : %f  imag : %f",cobj.real,cobj.imag);
return 0;
}
于 2012-11-19T18:45:01.337 回答