10059. Complex Number

I'm a slow walker, but I never walk backwards.

題目描述

實作複數加法、減法、乘法。令 $i = \sqrt{-1}$。

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "complex.h"
 
int main() {
    complex (*FUNC[])(complex *, complex *) = {
        complex_add, complex_sub, complex_mul
    };
    int cmd;
    float x, y, p, q;
    while (scanf("%d %f %f %f %f", &cmd, &x, &y, &p, &q) == 5) {
        complex *A = (complex *) malloc(sizeof(complex));
        complex *B = (complex *) malloc(sizeof(complex));
        init(A, x, y), init(B, p, q);
        complex C = FUNC[cmd](A, B);
        complex_print(&C);
    }
    return 0;
}

complex.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _COMPLEX_H
#define _COMPLEX_H
 
/*
    define structure complex
*/
 
void init(complex *c, float a, float b);
void complex_print(complex *x);
complex complex_add(complex *x, complex *y);
complex complex_sub(complex *x, complex *y);
complex complex_mul(complex *x, complex *y);
#endif

Sample Input

1
2
3
0 3 2 1 4
1 3 2 1 4
2 3 2 1 4

Sample Output

1
2
3
4.000+6.000i
2.000-2.000i
-5.000+14.000i

printf format

1
2
float a, b;
printf("%.3f%+.3fi\n", a, b);

Discussion