2012-11-19 48 views
-1

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

typedef struct { 
    float real, imag; 
} complex_t; 


complex_t read_complex(void) 
{ 

} 

我该如何扫描输入?

+6

你重新格式化代码。但你有什么尝试? –

回答

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); 
} 
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; 
} 
+0

我希望你得到这个 – Omkant