C语言 复数运算
复数是由实部和虚部组成的数字,可以表示为a+bi的形式,其中a为实部,b为虚部,i为虚数单位。在数学中,复数也可以进行加减乘除等运算。本文将使用c模块化方法编写标准c语言程序,实现两个复数的相加、相减、相乘与相除,并输出。
复数结构体定义
首先,我们需要定义一个结构体来表示复数,包括实部和虚部。
typedef struct Complex {
double real;
double imaginary;
} Complex;
复数加法
复数的加法运算规则为:(a+bi) + (c+di) = (a+c) + (b+d)i。下面是对应的c函数实现:
Complex add(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imaginary = c1.imaginary + c2.imaginary;
return result;
}
复数减法
复数的减法运算规则为:(a+bi) – (c+di) = (a-c) + (b-d)i。下面是对应的c函数实现:
Complex subtract(Complex c1, Complex c2) {
Complex result;
result.real = c1.real - c2.real;
result.imaginary = c1.imaginary - c2.imaginary;
return result;
}
复数乘法
复数的乘法运算规则为:(a+bi) * (c+di) = ac – bd + (ad + bc)i。下面是对应的c函数实现:
Complex multiply(Complex c1, Complex c2) {
Complex result;
result.real = c1.real * c2.real - c1.imaginary * c2.imaginary;
result.imaginary = c1.real * c2.imaginary + c1.imaginary * c2.real;
return result;
}
复数除法
复数的除法运算比较复杂,需要将分子和分母同时乘以分母的共轭复数,然后进行简化。规则为:(a+bi) / (c+di) = (ac+bd)/(c^2+d^2) + ((bc-ad)/(c^2+d^2))i。下面是对应的c函数实现:
Complex divide(Complex c1, Complex c2) {
Complex result;
double denominator = c2.real * c2.real + c2.imaginary * c2.imaginary;
result.real = (c1.real * c2.real + c1.imaginary * c2.imaginary) / denominator;
result.imaginary = (c1.imaginary * c2.real - c1.real * c2.imaginary) / denominator;
return result;
}
测试
现在我们来测试上述函数,分别对两个复数进行加减乘除操作,并输出。
int main() {
Complex c1 = {3.0, 4.0};
Complex c2 = {1.0, 2.0};
// 加法
Complex sum = add(c1, c2);
printf("Sum: %f + %fi\n", sum.real, sum.imaginary);
// 减法
Complex difference = subtract(c1, c2);
printf("Difference: %f + %fi\n", difference.real, difference.imaginary);
// 乘法
Complex product = multiply(c1, c2);
printf("Product: %f + %fi\n", product.real, product.imaginary);
// 除法
Complex quotient = divide(c1, c2);
printf("Quotient: %f + %fi\n", quotient.real, quotient.imaginary);
return 0;
}
运行以上代码,我们可以得到以下输出:
Sum: 4.000000 + 6.000000i
Difference: 2.000000 + 2.000000i
Product: -5.000000 + 10.000000i
Quotient: 2.200000 + -0.400000i
通过上面的实例,我们成功地实现了复数的加减乘除运算,并输出了计算结果。复数运算在实际生活和工作中有着广泛的应用,掌握复数运算将有助于我们解决更多的实际问题。