C语言设计一个可进行复数运算的演示程序。要求实现下列6种基本运算: (1)由输入的实部和虚部生成一个复数。 (2)两个复数求和。 (3)两个复数求差 (4)两个复数求积 (5)从已知复数中分离出实部。 (6)从已知复数中分离出虚部
时间: 2024-06-01 20:10:22 浏览: 99
复数的基本运算(C语言).doc
#include <stdio.h>
typedef struct {
double real;
double imag;
} Complex; // 定义复数类型
void create(Complex *c, double real, double imag) {
c->real = real;
c->imag = imag;
}
void add(Complex *c1, Complex *c2, Complex *result) {
result->real = c1->real + c2->real;
result->imag = c1->imag + c2->imag;
}
void sub(Complex *c1, Complex *c2, Complex *result) {
result->real = c1->real - c2->real;
result->imag = c1->imag - c2->imag;
}
void mul(Complex *c1, Complex *c2, Complex *result) {
result->real = c1->real * c2->real - c1->imag * c2->imag;
result->imag = c1->real * c2->imag + c1->imag * c2->real;
}
double getReal(Complex *c) {
return c->real;
}
double getImag(Complex *c) {
return c->imag;
}
int main() {
Complex c1, c2, result;
create(&c1, 2, 3);
create(&c2, 4, 5);
add(&c1, &c2, &result);
printf("(%f + %fi) + (%f + %fi) = %f + %fi\n", c1.real, c1.imag, c2.real, c2.imag, result.real, result.imag);
sub(&c1, &c2, &result);
printf("(%f + %fi) - (%f + %fi) = %f + %fi\n", c1.real, c1.imag, c2.real, c2.imag, result.real, result.imag);
mul(&c1, &c2, &result);
printf("(%f + %fi) * (%f + %fi) = %f + %fi\n", c1.real, c1.imag, c2.real, c2.imag, result.real, result.imag);
printf("Real part of (%f + %fi) is %f\n", c1.real, c1.imag, getReal(&c1));
printf("Imaginary part of (%f + %fi) is %f\n", c1.real, c1.imag, getImag(&c1));
return 0;
}
阅读全文