复数四则运算c语言pta
时间: 2024-10-04 19:00:23 浏览: 105
用C语言实现复数的四则运算
在C语言中,处理复数四则运算(加法、减法、乘法和除法)通常需要自定义数据结构来存储实部和虚部,并提供相应的函数来进行操作。以下是一个简单的例子:
首先,我们定义一个复数结构体:
```c
typedef struct {
double real; // 实部
double imag; // 虚部
} Complex;
```
接下来,我们可以编写四个基本的复数运算函数:
```c
// 加法
Complex add(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
// 减法
Complex subtract(Complex c1, Complex c2) {
Complex result;
result.real = c1.real - c2.real;
result.imag = c1.imag - c2.imag;
return result;
}
// 乘法
Complex multiply(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;
}
// 分母为非零的除法
Complex divide(Complex c1, Complex c2) {
if (c2.real != 0 && c2.imag == 0) { // 防止除以零的情况
Complex reciprocal;
reciprocal.real = 1 / c2.real;
reciprocal.imag = 0;
return multiply(c1, reciprocal);
} else {
printf("Invalid operation: Division by zero is not allowed.\n");
return c1; // 或者返回错误处理的结果
}
}
```
使用这些函数时,你可以创建复数对象并执行相应运算:
```c
Complex num1 = {3.0, 4.0};
Complex num2 = {1.0, 2.0};
Complex sum = add(num1, num2);
Complex difference = subtract(num1, num2);
Complex product = multiply(num1, num2);
Complex quotient = divide(num1, num2); // 运行前检查是否可以除以零
printf("Sum: (%lf, %lf)\n", sum.real, sum.imag);
printf("Difference: (%lf, %lf)\n", difference.real, difference.imag);
printf("Product: (%lf, %lf)\n", product.real, product.imag);
```
阅读全文