能简化一下上面的代码吗?
时间: 2023-08-17 18:06:14 浏览: 40
当然可以,以下是一种简化的实现方式:
```c
#include <stdio.h>
typedef struct {
double real, imag;
} Complex;
Complex multiply(Complex c1, Complex c2) {
return (Complex){c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real};
}
int main() {
Complex c1, c2;
printf("Enter first complex number: ");
scanf("%lf%lf", &c1.real, &c1.imag);
printf("Enter second complex number: ");
scanf("%lf%lf", &c2.real, &c2.imag);
Complex product = multiply(c1, c2);
printf("Product = %.2lf + %.2lfi\n", product.real, product.imag);
return 0;
}
```
在这个简化的版本中,我们使用一个匿名结构体来返回两个虚数的乘积,这样就不需要再定义一个 `Complex` 结构体类型了。此外,在 `typedef` 语句中,我们将 `real` 和 `imag` 合并到了一行中,这样代码就显得更加简洁了。
另外,我们也省略了变量 `ans` 的声明和使用,直接将 `multiply` 函数的返回值赋值给了 `product` 变量。