C语言用结构体编程复数四则运算
时间: 2024-11-28 20:20:55 浏览: 10
在C语言中,可以使用结构体(struct)来创建复数类型,并实现基本的四则运算。首先,我们需要定义一个表示复数的结构体,包含实部(real)和虚部(imaginary)两个成员:
```c
#include <stdio.h>
typedef struct {
double real;
double imaginary;
} Complex;
```
接下来,我们可以为这个结构体定义加法、减法、乘法和除法的运算函数:
```c
Complex add(Complex a, Complex b) {
Complex result;
result.real = a.real + b.real;
result.imaginary = a.imaginary + b.imaginary;
return result;
}
Complex subtract(Complex a, Complex b) {
Complex result;
result.real = a.real - b.real;
result.imaginary = a.imaginary - b.imaginary;
return result;
}
Complex multiply(Complex a, Complex b) {
Complex result;
result.real = a.real * b.real - a.imaginary * b.imaginary;
result.imaginary = a.real * b.imaginary + a.imaginary * b.real;
return result;
}
// 为了处理除法,需要防止除以零的情况
double denominator = sqrt(b.real * b.real + b.imaginary * b.imaginary);
if (denominator == 0) {
printf("Error: Division by zero.\n");
return NULL; // 或者返回一个特殊的值
}
Complex divide(Complex a, Complex b) {
Complex result;
result.real = (a.real * b.real + a.imaginary * b.imaginary) / denominator;
result.imaginary = (a.imaginary * b.real - a.real * b.imaginary) / denominator;
return result;
}
```
然后你可以像这样使用这些函数进行复数运算:
```c
int main() {
Complex c1 = {3, 4};
Complex c2 = {5, 6};
Complex sum = add(c1, c2);
Complex diff = subtract(c1, c2);
Complex prod = multiply(c1, c2);
Complex quotient;
if (quotient = divide(c1, c2)) {
printf("Sum: (%lf, %lf)\n", sum.real, sum.imaginary);
printf("Difference: (%lf, %lf)\n", diff.real, diff.imaginary);
printf("Product: (%lf, %lf)\n", prod.real, prod.imaginary);
printf("Quotient: (%lf, %lf)\n", quotient.real, quotient.imaginary);
}
return 0;
}
```
阅读全文