C语言实现复数的四则运算
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
float realPart;
float imagePart;
}Complex;
void initialComplex(Complex &C,float r,float i)//初始化复数
{
C.realPart = r;
C.imagePart = i;
}
void sum(Complex &C, Complex A, Complex B)//求两个复数的和
{
C.realPart = A.realPart + B.realPart;
C.imagePart = A.imagePart + B.imagePart;
}
void mul(Complex &C, Complex A, Complex B)//求两个复数的乘法
{
C.realPart = A.realPart*B.realPart - A.imagePart*B.imagePart;
C.imagePart = A.realPart*B.imagePart + A.imagePart*B.realPart;
}
void divid(Complex &C,Complex A,Complex B)//求两个复数的除法
{
C.realPart = A.realPart*B.realPart + A.imagePart*B.imagePart;
C.imagePart = B.imagePart *A.realPart + A.imagePart*B.realPart;
float f = B.realPart + B.imagePart*B.imagePart;//分母
if (f != 0)
{
C.realPart = C.realPart / f;
C.imagePart = C.imagePart / f;
}
else
{
printf("复数的除法中分母为0,异常退出!");
exit(0);//使用exit函数必须使用stdlib.h头文件
}
}
void main()
{
Complex z, z1, z2,z3,z4;
initialComplex(z, 1, 2);
initialComplex(z1, -1, 1 );
sum(z2, z, z1);
mul(z3, z, z1);
divid(z4, z, z1);
printf("复数z:%f%+fi\n", z.realPart, z.imagePart);
printf("复数z1:%f%+fi\n", z1.realPart, z1.imagePart);
printf("z+z1:%f%+fi\n", z2.realPart, z2.imagePart);
printf("z*z1:%f%+fi\n", z3.realPart, z3.imagePart);
printf("z/z1:%f%+fi\n", z4.realPart, z4.imagePart);
}