#include<stdio.h>
#include<math.h>
#include<string.h>
typedef struct complex{
double real;
double virt;
}COM;
//复数求和的实现函数
COM summation(COM num1,COM num2){
COM result;
result.real=num1.real+num2.real;
result.virt=num1.virt+num2.virt;
return result;
}
//复数乘积的实现函数 (a+bi)*(c+di) = (ac-bd)+(bc+ad)i
COM multiplication(COM num1,COM num2){
COM result;
result.real= num1.real*num2.real-num1.virt*num2.virt;
result.virt= num1.virt*num2.real + num1.real*num2.virt;
return result;
}
//复数除法的实现 (a+bi)/(c+di)=(ac+bd)/(c2+d2) +((bc-ad)/(c2+d2))i
COM division(COM num1,COM num2){
COM result;
result.real=(num1.real*num2.real+num1.virt*num2.virt)/(num2.real*num2.real+num2.virt*num2.virt);
result.virt=(num1.virt*num2.real-num1.real*num2.virt)/(num2.real*num2.real+num2.virt*num2.virt);
return result;
}
// 将结果进行输出
void printResult(COM result){
double virtPart=fabs(result.virt);
char virtPartStr[100],realPartStr[100];
sprintf(virtPartStr,"%lf",virtPart);
sprintf(realPartStr,"%lf",result.real);
//清除末尾0,如将1.16000输出为1.16
for(int i=strlen(virtPartStr);i>0;i--){
if(virtPartStr[i]=='0'&&virtPartStr[i-1]!='0'){
virtPartStr[i]='\0';
break;
}
}
for(int i=strlen(realPartStr);i>0;i--){
if(realPartStr[i]=='0'&&realPartStr[i-1]!='0'){
realPartStr[i]='\0';
break;
}
}
//输出处理后的结果
if(result.real!=0){
if(result.virt<0){
printf("%s-i%s",realPartStr,virtPartStr);
}else if(result.virt>0){
printf("%s+i%s",realPartStr,virtPartStr);
}else{
int endIndex=strlen(realPartStr)-1;
realPartStr[endIndex]='\0';
printf("%s",realPartStr);
}
}else{
if((strcmp(virtPartStr,"0")==0)){
printf("-i%s",realPartStr,virtPartStr);
}else if(result.virt>0){
printf("+i%s",realPartStr,virtPartStr);
}else{
printf("0");
}
}
printf("\n");
}
int main(){
printf("结构体 复数运算 By Titan!\n\n");
COM number1,number2,result;
// ----- <做加减运算> ------
//第一组测试 (7.7-8i)+(-2.3)
number1={7.7,-8};
number2={-2.3,0};
result=summation(number1,number2);
printf("(7.7-8i)+(-2.3) = ");
printResult(result);
//第二组测试 (0+0)
number1={0,0};
number2={0,0};
result=summation(number1,number2);
printf("(0+0) = ") ;
printResult(result);
//----- <做乘运算> ------
// (2+2i)*(3-1.55i)
number1={2,2};
number2={3,-1.55};
result=multiplication(number1,number2);
printf("(2+2i)*(3-1.55i) = ");
printResult(result);
//----- <做除运算> ------
// (7.5+2i)/(3.5+3i)
number1={7.5,2};
number2={3.5,3};
result=division(number1,number2);
printf("(7.5+2i)/(3.5+3i) = ") ;
printResult(result);
// 对于复数的读入和分离输出,只需要相应的取 COM的成员 real和virt即可.
}