11001
题目
实现复数结构体,并实现加、减、乘、除运算,以及求模长和辐角。
解析
- 定义结构体
- 加减乘除
- 模长/辐角
- 打印复数
答案
c
typedef struct {
double real;
double imag;
} my_complex;
my_complex complex_add(my_complex a, my_complex b) {
my_complex result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
my_complex complex_subtract(my_complex a, my_complex b) {
my_complex result;
result.real = a.real - b.real;
result.imag = a.imag - b.imag;
return result;
}
my_complex complex_multiply(my_complex a, my_complex b) {
my_complex result;
result.real = a.real * b.real - a.imag * b.imag;
result.imag = a.real * b.imag + a.imag * b.real;
return result;
}
my_complex complex_divide(my_complex a, my_complex b) {
my_complex result;
assert(b.real * b.real + b.imag * b.imag; != 0);
result.real = (a.real * b.real + a.imag * b.imag) / denominator;
result.imag = (a.imag * b.real - a.real * b.imag) / denominator;
return result;
}
double complex_magnitude(my_complex c) {
return sqrt(c.real * c.real + c.imag * c.imag);
}
double complex_argument(my_complex c) {
return atan2(c.imag, c.real);
}
void print_complex(my_complex c) {
if(isnan(c.real) || isnan(c.imag)){
printf("Error: Invalid complex number.\n");
return;
}
printf("%g + %gi", c.real, c.imag);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49