C语言如何设计一个可进行复数运算的演示程序。要求实现下列6种基本运算: (1)由输入的实部和虚部生成一个复数。 (2)两个复数求和。 (3)两个复数求差 (4)两个复数求积 (5)从已知复数中分离出实部。 (6)从已知复数中分离出虚部
时间: 2024-05-06 18:20:21 浏览: 197
下面是一个简单的可进行复数运算的演示程序:
```c
#include <stdio.h>
typedef struct {
double real;
double imag;
} Complex;
Complex create_complex(double real, double imag) {
Complex c;
c.real = real;
c.imag = imag;
return c;
}
Complex add_complex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
Complex sub_complex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real - c2.real;
result.imag = c1.imag - c2.imag;
return result;
}
Complex mul_complex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}
double real_part(Complex c) {
return c.real;
}
double imag_part(Complex c) {
return c.imag;
}
int main() {
double real1, imag1, real2, imag2;
printf("Enter the real and imaginary parts of the first complex number: ");
scanf("%lf %lf", &real1, &imag1);
printf("Enter the real and imaginary parts of the second complex number: ");
scanf("%lf %lf", &real2, &imag2);
Complex c1 = create_complex(real1, imag1);
Complex c2 = create_complex(real2, imag2);
printf("The sum of the two complex numbers is: %.2f + %.2fi\n", add_complex(c1, c2).real, add_complex(c1, c2).imag);
printf("The difference of the two complex numbers is: %.2f + %.2fi\n", sub_complex(c1, c2).real, sub_complex(c1, c2).imag);
printf("The product of the two complex numbers is: %.2f + %.2fi\n", mul_complex(c1, c2).real, mul_complex(c1, c2).imag);
printf("The real part of the first complex number is: %.2f\n", real_part(c1));
printf("The imaginary part of the first complex number is: %.2f\n", imag_part(c1));
return 0;
}
```
程序中定义了一个复数结构体 `Complex`,包含实部和虚部两个成员变量。然后通过函数实现了六种基本运算:
1. `create_complex`:由输入的实部和虚部生成一个复数。
2. `add_complex`:两个复数求和。
3. `sub_complex`:两个复数求差。
4. `mul_complex`:两个复数求积。
5. `real_part`:从已知复数中分离出实部。
6. `imag_part`:从已知复数中分离出虚部。
在 `main` 函数中,先读入两个复数的实部和虚部,然后分别用 `create_complex` 函数生成两个复数,再分别调用其他五个函数进行操作,并输出结果。
注意,由于复数的加、减、乘运算都需要涉及实部和虚部,因此在函数实现时需要分别对实部和虚部进行计算。
阅读全文
相关推荐














