用结构体定义复数,并求两个复数的乘积
时间: 2024-02-18 14:05:14 浏览: 22
可以使用以下结构体定义复数,并编写一个函数 `complex_multiply` 来计算两个复数的乘积:
```
#include <stdio.h>
struct Complex {
double real; // 实部
double imag; // 虚部
};
// 计算两个复数的乘积
struct Complex complex_multiply(struct Complex z1, struct Complex z2) {
struct Complex result;
result.real = z1.real * z2.real - z1.imag * z2.imag;
result.imag = z1.real * z2.imag + z1.imag * z2.real;
return result;
}
int main() {
struct Complex z1 = { 1.0, 2.0 };
struct Complex z2 = { 3.0, 4.0 };
struct Complex product = complex_multiply(z1, z2);
printf("z1 * z2 = %.2f + %.2fi\n", product.real, product.imag);
return 0;
}
```
在上面的代码中,我们定义了一个结构体 `Complex` 来表示复数,然后编写了一个函数 `complex_multiply` 来计算两个复数的乘积。在 `main` 函数中,我们定义了两个复数 `z1` 和 `z2`,并调用 `complex_multiply` 函数计算它们的乘积。最后输出结果。