用c语言写一个程序实现定义一个结构,并编写程序,完成复数的加、减、乘、除运算
时间: 2024-09-27 22:15:53 浏览: 44
在 C 语言中,我们可以定义一个结构体(struct)来表示复数,然后编写函数来实现复数的加法、减法、乘法和除法运算。首先,我们定义一个名为 `complex` 的结构体:
```c
#include <stdio.h>
// 定义复数结构体
typedef struct {
double real; // 实部
double imag; // 虚部
} complex;
// 加法操作
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;
}
// 除法操作,假设分母不为0
complex divide(complex c1, complex c2) {
complex denominator;
denominator.real = c2.real * c2.real + c2.imag * c2.imag;
if (denominator.real != 0) {
complex numerator = {c1.real * c2.real + c1.imag * c2.imag, c1.real * c2.imag - c1.imag * c2.real};
complex result;
result.real = numerator.real / denominator.real;
result.imag = numerator.imag / denominator.real;
return result;
} else {
printf("Error: Division by zero is not allowed.\n");
return {-1, -1}; // 返回错误处理结果
}
}
int main() {
complex num1 = {3, 4}, num2 = {5, 6};
printf("Addition: (%lf + %lj) + (%lf + %lj) = (%lf + %lj)\n", num1.real, num1.imag, num2.real, num2.imag, add(num1, num2).real, add(num1, num2).imag);
printf("Subtraction: (%lf + %lj) - (%lf + %lj) = (%lf + %lj)\n", num1.real, num1.imag, num2.real, num2.imag, subtract(num1, num2).real, subtract(num1, num2).imag);
printf("Multiplication: (%lf + %lj) * (%lf + %lj) = (%lf + %lj)\n", num1.real, num1.imag, num2.real, num2.imag, multiply(num1, num2).real, multiply(num1, num2).imag);
complex quotient;
if (divide(num1, num2).real != -1) {
printf("Division: (%lf + %lj) / (%lf + %lj) = (%lf + %lj)\n", num1.real, num1.imag, num2.real, num2.imag, divide(num1, num2).real, divide(num1, num2).imag);
}
return 0;
}
```
这个程序定义了一个 `complex` 结构体,以及四个函数分别实现了加、减、乘、除四种运算。在 `main()` 函数中创建了两个复数并进行了运算。注意,这里的除法操作会检查分母是否为零,若为零则返回错误信息。
阅读全文