c语言复数的四则运算
时间: 2024-10-17 21:01:40 浏览: 35
用C语言实现复数的四则运算
在C语言中,复数的四则运算通常涉及到结构体(struct)的使用,因为C标准库本身并不支持复数直接操作。我们可以创建一个名为`complex`的结构体,包含实部(real)和虚部(imaginary)两个成员,来进行复数的加减乘除。
```c
#include <stdio.h>
typedef struct {
double real;
double imag;
} complex;
complex add(complex a, complex b) {
return (complex) {a.real + b.real, a.imag + b.imag};
}
complex subtract(complex a, complex b) {
return (complex) {a.real - b.real, a.imag - b.imag};
}
complex multiply(complex a, complex b) {
double real = a.real * b.real - a.imag * b.imag;
double imag = a.real * b.imag + a.imag * b.real;
return (complex) {real, imag};
}
complex divide(complex a, complex b) {
double denominator = b.real * b.real + b.imag * b.imag;
if (denominator == 0) {
printf("Error: Division by zero.\n");
return (complex){0, 0}; // 或者处理特殊情况
}
double real = (a.real * b.real + a.imag * b.imag) / denominator;
double imag = (a.imag * b.real - a.real * b.imag) / denominator;
return (complex) {real, imag};
}
int main() {
complex num1 = {3, 4};
complex num2 = {5, 6};
complex sum = add(num1, num2);
complex diff = subtract(num1, num2);
complex prod = multiply(num1, num2);
complex quot = divide(num1, num2);
printf("Sum: (%lf, %lf)\n", sum.real, sum.imag);
printf("Difference: (%lf, %lf)\n", diff.real, diff.imag);
printf("Product: (%lf, %lf)\n", prod.real, prod.imag);
printf("Quotient: (%lf, %lf)\n", quot.real, quot.imag);
return 0;
}
```
阅读全文