复数运算c程序
#include <stdio.h>
#include <stdlib.h>
typedef struct{
float rmz;
float lmz;
}complex;
//构造一个复数
complex getAComplex(float a,float b){
complex complex1;
complex1.rmz=a;
complex1.lmz=b;
return complex1;
}
//两个复数求和
complex addComplex(complex complex1,complex complex2)
{ complex complex3;
complex3.rmz=complex1.rmz+complex2.rmz;
complex3.lmz=complex1.lmz+complex2.lmz;
return complex3;
}
//求两个复数的差
complex subComplex(complex complex1,complex complex2)
{
complex complex3;
complex3.rmz=complex1.rmz-complex2.rmz;
complex3.lmz=complex1.lmz-complex2.lmz;
return complex3;
}
//求两个复数的积
complex productComplex(complex complex1,complex complex2)
{
complex complex3;
complex3.rmz=complex1.rmz*complex2.rmz-complex1.lmz*complex2.lmz;
complex3.lmz=complex1.lmz*complex2.rmz+complex2.lmz*complex2.rmz;
return complex3;
}
//分离出实部
float getComplexRmz(complex complex1)
{
return complex1.rmz;
}
//分离出虚部
float getComplexLmz(complex complex1)
{
return complex1.lmz;
}
//打印复数
void PrintCom(complex com1)
{
if(com1.rmz>0||com1.lmz==0)
{
if(com1.rmz!=0&&com1.lmz!=0)
printf("%.2f+i%.2f\n",com1.rmz,com1.lmz);
else if(com1.rmz==0&&com1.lmz!=0)
printf("i%.2f\n",com1.lmz);
else if(com1.rmz!=0&&com1.lmz==0)
printf("%.2f\n",com1.rmz);
else if(com1.rmz==0&&com1.lmz==0)
printf("%.2f\n",com1.rmz);
}
else
{
www.751com.cn
printf("%.2f-i%.2f\n",com1.rmz,-com1.lmz);
else if(com1.rmz==0&&com1.lmz!=0)
printf("-i%.2f\n",-com1.lmz);
else if(com1.rmz!=0&&com1.lmz==0)
printf("%.2f\n",com1.rmz);
else if(com1.rmz==0&&com1.lmz==0)
printf("%.2f\n",com1.rmz);
}
}
//主函数
void main()
{
float rmz1,lmz1,rmz2,lmz2;
complex com1,com2,com3;
int choice;
printf("1.求两个复数的和\t2.求两个复数的差\t3.求两个复数的积\n4.分离出实部\t\t5.分离出虚部\t\t6.退出\n\n");
printf("输入第1个复数的实部和虚部:");
scanf("%f,%f",&rmz1,&lmz1);
com1=getAComplex(rmz1,lmz1);
printf("所生成的复数1为:");
PrintCom(com1);
printf("输入第2个复数的实部和虚部:");
scanf("%f,%f",&rmz2,&lmz2);
com2=getAComplex(rmz2,lmz2);
printf("所生成的复数2为:");
PrintCom(com2);
while(1){
printf("输入你的选择:");
scanf("%d",&choice);
switch(choice)
{
case 1:
com3=addComplex(com1,com2);
printf("两个复数的和为:");
PrintCom(com3);
break;
case 2:
com3= subComplex(com1,com2);
printf("两个复数的差为:");
PrintCom(com3);
break;
case 3:
com3=productComplex(com1,com2);
printf("两个复数的积为:");
PrintCom(com3);
break;
case 4:
printf("复数1的实部为:%.2f\n",getComplexRmz(com1));
printf("复数2的实部为:%.2f\n", getComplexRmz(com2));
break;
case 5:
printf("复数1的虚部为:%.2f\n",getComplexLmz(com1));
printf("复数2的虚部为:%.2f\n",getComplexLmz(com2));
break;
case 6:
break;
default:
printf("请输入1~6的数字!\n"); break;
}
if(choice==6) break;
}
}617