C语言版数据结构中复数的加减乘除运算代码
时间: 2024-09-06 08:05:18 浏览: 78
利用c语言完成复数的计算(共轭,加减乘除)
5星 · 资源好评率100%
在C语言中实现复数的加减乘除运算,首先需要定义复数的数据结构。通常复数由实部(real)和虚部(imaginary)组成。以下是一个简单的复数数据结构定义和对应的加减乘除运算的实现示例:
```c
#include <stdio.h>
// 定义复数结构体
typedef struct {
double real; // 实部
double imaginary; // 虚部
} Complex;
// 复数加法
Complex complex_add(Complex a, Complex b) {
Complex result;
result.real = a.real + b.real;
result.imaginary = a.imaginary + b.imaginary;
return result;
}
// 复数减法
Complex complex_subtract(Complex a, Complex b) {
Complex result;
result.real = a.real - b.real;
result.imaginary = a.imaginary - b.imaginary;
return result;
}
// 复数乘法
Complex 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;
}
// 复数除法
Complex complex_divide(Complex a, Complex b) {
Complex result;
double denominator = b.real * b.real + b.imaginary * b.imaginary;
if (denominator == 0) {
printf("除数不能为0\n");
return (Complex){0, 0}; // 非法除法结果
}
result.real = (a.real * b.real + a.imaginary * b.imaginary) / denominator;
result.imaginary = (a.imaginary * b.real - a.real * b.imaginary) / denominator;
return result;
}
int main() {
Complex c1 = {1.0, 2.0};
Complex c2 = {3.0, 4.0};
Complex sum, difference, product, quotient;
sum = complex_add(c1, c2);
printf("加法结果: %f + %fi\n", sum.real, sum.imaginary);
difference = complex_subtract(c1, c2);
printf("减法结果: %f + %fi\n", difference.real, difference.imaginary);
product = complex_multiply(c1, c2);
printf("乘法结果: %f + %fi\n", product.real, product.imaginary);
quotient = complex_divide(c1, c2);
printf("除法结果: %f + %fi\n", quotient.real, quotient.imaginary);
return 0;
}
```
在这段代码中,我们首先定义了一个`Complex`类型的结构体来表示复数。然后,通过函数`complex_add`, `complex_subtract`, `complex_multiply`, 和 `complex_divide`来实现复数的加、减、乘、除运算。在进行除法运算时,我们还检查了除数是否为零,以避免除以零的错误。最后在`main`函数中演示了如何使用这些函数。
阅读全文