用结构体和函数求两个复数之积
时间: 2024-05-07 18:20:29 浏览: 10
可以使用结构体表示复数,然后定义一个函数来计算两个复数的乘积。以下是一个示例代码:
```c
#include <stdio.h>
typedef struct {
double real;
double imag;
} complex;
complex multiply(complex c1, complex c2) {
complex result;
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c2.real * c1.imag;
return result;
}
int main() {
complex c1, c2, product;
printf("Enter the first complex number (a + bi): ");
scanf("%lf %lf", &c1.real, &c1.imag);
printf("Enter the second complex number (a + bi): ");
scanf("%lf %lf", &c2.real, &c2.imag);
product = multiply(c1, c2);
printf("The product is: %.2f + %.2fi\n", product.real, product.imag);
return 0;
}
```
在上面的代码中,我们首先定义了一个结构体 `complex`,其中包含实部和虚部两个成员。然后我们定义了一个函数 `multiply`,它接受两个复数作为参数,返回它们的乘积。在 `main` 函数中,我们通过用户输入来获取两个复数,然后调用 `multiply` 函数来计算它们的乘积,并将结果存储在 `product` 变量中。最后,我们在屏幕上输出乘积的实部和虚部。