wzpan
9/2/2013 - 5:18 AM

## C - struct

C - struct

``````#include <math.h>

struct ComplexStruct {
// 定义复数的结构体
double x, y;
};

double real_part(struct ComplexStruct z){
// 返回复数的实部
return z.x;
}

double img_part(struct ComplexStruct z){
// 返回复数的虚部
return z.y;
}

double magnitude(struct ComplexStruct z){
// 返回复数的模
return sqrt(z.x * z.x + z.y * z.y);
}

double angle(struct ComplexStruct z){
// 返回复数的辐角
return atan2(z.y, z.x);
}

struct ComplexStruct make_from_real_img(double x, double y){
// 用实部和虚部构造复数结构体
struct ComplexStruct z;
z.x = x;
z.y = y;
return z;
}

struct ComplexStruct make_from_mag_ang(double r, double A){
// 用辐角和模构造复数结构体
struct ComplexStruct z;
z.x = r * cos(A);
z.y = r * sin(A);
return z;
}

// 定义复数的加减乘除运算
struct ComplexStruct add_complex(struct ComplexStruct z1, struct ComplexStruct z2){
return make_from_real_img(
real_part(z1) + real_part(z2),
img_part(z1) + img_part(z2)
);
}

struct ComplexStruct sub_complex(struct ComplexStruct z1, struct ComplexStruct z2){
return make_from_real_img(
real_part(z1) - real_part(z2),
img_part(z1) - img_part(z2)
);
}

struct ComplexStruct mul_complex(struct ComplexStruct z1, struct ComplexStruct z2){
return make_from_mag_ang(
magnitude(z1) * magnitude(z2),
angle(z1) + angle(z2)
);
}

struct ComplexStruct div_complex(struct ComplexStruct z1, struct ComplexStruct z2){
return make_from_mag_ang(
magnitude(z1) / magnitude(z2),
angle(z1) - angle(z2)
);
}``````