复数的四则运算
纯C语言版:
#include<stdio.h>
#include<math.h>
struct cpxNum
{
double a,b;
};
cpxNum cplus(cpxNum c1,cpxNum c2); //加
cpxNum cmilus(cpxNum c1,cpxNum c2); //减
cpxNum cmultiply(cpxNum c1,cpxNum c2); //乘
cpxNum cdivide(cpxNum c1,cpxNum c2); //除
int main()
{
cpxNum c1, c2,c3;
double real,imag;
printf("请输入第一个复数的实部和虚部: ");
scanf("%lf %lf",&real,&imag);
printf("您生成的第一个复数是: ");
c1.a=real;
c1.b=imag;
printf("%f+%fi\n",real,imag);
printf("请输入第二个复数的实部和虚部: ");
scanf("%lf %lf",&real,&imag);
printf("您生成的第二个复数是: ");
c2.a=real;
c2.b=imag;
printf("%f+%fi\n",real,imag);
printf("***********复数运算测试*************\n");
printf("c1 + c2的结果是: ");
c3=cplus(c1, c2);
if(c3.b<0)
printf("%lf - %lfi\n",c3.a,fabs(c3.b));
else
printf("%lf + %lfi\n",c3.a,c3.b);
printf("c1 - c2的结果是: ");;
c3=cmilus(c1, c2);
if(c3.b<0)
printf("%lf - %lfi\n",c3.a,fabs(c3.b));
else
printf("%lf+%lfi\n",c3.a,c3.b);
printf("c1 * c2的结果是: ");
c3=cmultiply(c1, c2);
if(c3.b<0)
printf("%lf - %lfi\n",c3.a,fabs(c3.b));
else
printf("%lf+%lfi\n",c3.a,c3.b);
printf("c1 / c2的结果是: ");
c3=cdivide(c1, c2);
if(c3.b<0)
printf("%lf - %lfi\n",c3.a,fabs(c3.b));
else
printf("%lf+%lfi\n",c3.a,c3.b);
printf("**********复数运算测试结束***********\n");
return 0;
}
cpxNum cplus(cpxNum c1,cpxNum c2)
{
cpxNum c3;
c3.a=c1.a+c2.a;
c3.b=c1.b+c2.b;
return c3;
}
cpxNum cmilus(cpxNum c1,cpxNum c2)
{
cpxNum c3;
c3.a=c1.a-c2.a;
c3.b=c1.b-c2.b;
return c3;
}
cpxNum cmultiply(cpxNum c1,cpxNum c2)
{
cpxNum c3;
c3.a=c1.a*c2.a-c1.b*c2.b;
c3.b=c1.a*c2.b+c1.b*c2.a;
return c3;
}
cpxNum cdivide(cpxNum c1,cpxNum c2)
{
cpxNum c3;
c3.a=c1.a*c2.a+c1.b*c2.b;
c3.b=c1.b*c2.a-c1.a*c2.b;
return c3;
}
//优化了虚部的表示
用结构体挺简单的;
贴张运行效果图: