一个可以进行复数运算的演示程序用c语言
时间: 2023-04-26 15:05:53 浏览: 148
以下是一个可以进行复数运算的演示程序,使用C语言编写:
#include <stdio.h>
typedef struct {
double real;
double imag;
} complex;
complex add(complex a, complex b) {
complex result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
complex subtract(complex a, complex b) {
complex result;
result.real = a.real - b.real;
result.imag = a.imag - b.imag;
return result;
}
complex multiply(complex a, complex b) {
complex result;
result.real = a.real * b.real - a.imag * b.imag;
result.imag = a.real * b.imag + a.imag * b.real;
return result;
}
complex divide(complex a, complex b) {
complex result;
double denominator = b.real * b.real + b.imag * b.imag;
result.real = (a.real * b.real + a.imag * b.imag) / denominator;
result.imag = (a.imag * b.real - a.real * b.imag) / denominator;
return result;
}
void print_complex(complex c) {
if (c.imag >= 0) {
printf("%.2f + %.2fi\n", c.real, c.imag);
} else {
printf("%.2f - %.2fi\n", c.real, -c.imag);
}
}
int main() {
complex a = {1.0, 2.0};
complex b = {3.0, -4.0};
complex c;
printf("a = ");
print_complex(a);
printf("b = ");
print_complex(b);
c = add(a, b);
printf("a + b = ");
print_complex(c);
c = subtract(a, b);
printf("a - b = ");
print_complex(c);
c = multiply(a, b);
printf("a * b = ");
print_complex(c);
c = divide(a, b);
printf("a / b = ");
print_complex(c);
return 0;
}
这个程序定义了一个复数结构体,包含实部和虚部两个成员。然后定义了四个函数,分别实现复数的加、减、乘、除运算。最后在主函数中对两个复数进行运算,并输出结果。
阅读全文