7-36 复数四则运算(15 分)

7-36 复数四则运算(15 分)

本题要求编写程序,计算2个复数的和、差、积、商。

输入格式:

输入在一行中按照a1 b1 a2 b2的格式给出2个复数C1=a1+b1i和C2=a2+b2i的实部和虚部。题目保证C2不为0。

输出格式:

分别在4行中按照(a1+b1i) 运算符 (a2+b2i) = 结果的格式顺序输出2个复数的和、差、积、商,数字精确到小数点后1位。如果结果的实部或者虚部为0,则不输出。如果结果为0,则输出0.0。

输入样例1:

1
2 3.08 -2.04 5.06

输出样例1:

1
2
3
4
(2.0+3.1i) + (-2.0+5.1i) = 8.1i
(2.0+3.1i) - (-2.0+5.1i) = 4.0-2.0i
(2.0+3.1i) * (-2.0+5.1i) = -19.7+3.8i
(2.0+3.1i) / (-2.0+5.1i) = 0.4-0.6i

输入样例2:

1
1 1 -1 -1.01

输出样例2:

1
2
3
4
(1.0+1.0i) + (-1.0-1.0i) = 0.0
(1.0+1.0i) - (-1.0-1.0i) = 2.0+2.0i
(1.0+1.0i) * (-1.0-1.0i) = -2.0i
(1.0+1.0i) / (-1.0-1.0i) = -1.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//两个复数运算前不变化,但输出时要保留后一位;
//运算结果,由题意,要先保留一位小数
#include <stdio.h>
#include <math.h>
struct data
{
double num1;
double num2;
};
char item[4]="+-*/";
void myprintf(double num1,double num2,int flag)
{
if(flag){//运算结果输出
if(num1==0&&num2==0)
printf("0.0");
else{
if(num1!=0&&num2==0)
printf("%.1f",num1);
else if(num1==0&&num2!=0)
printf("%.1fi",num2);
else{
printf("%.1f",num1);
if(num2>0)
printf("+%.1fi",num2);
else
printf("%.1fi",num2);
}
}
}
else{//复数输出
if(num2<0){
printf("%.1f%.1fi",num1,num2);
}else{
printf("%.1f+%.1fi",num1,num2);
}
}

}
double simpl(double num){//运算结果保留一位小数
if(num>0)
num=(double)floor((num+0.05)*10)/10;
else if(num<0){
num=fabs(num);
num=-(double)floor((num+0.05)*10)/10;
}
return num;
}
void getresult(struct data cal[],int time)//运算
{
double temp1,temp2,temp;
switch(time)
{
case 0:cal[2].num1=cal[0].num1+cal[1].num1;
cal[2].num2=cal[0].num2+cal[1].num2;
break;
case 1:cal[2].num1=cal[0].num1-cal[1].num1;
cal[2].num2=cal[0].num2-cal[1].num2;
break;
case 2:cal[2].num1=cal[0].num1*cal[1].num1-cal[0].num2*cal[1].num2;
cal[2].num2=cal[0].num1*cal[1].num2+cal[0].num2*cal[1].num1;
break;
case 3:temp1=cal[0].num1*cal[1].num1+cal[0].num2*cal[1].num2;
temp2=cal[0].num2*cal[1].num1-cal[0].num1*cal[1].num2;
temp=cal[1].num2*cal[1].num2+cal[1].num1*cal[1].num1;
cal[2].num1=temp1/temp;
cal[2].num2=temp2/temp;
break;
}
cal[2].num1=simpl(cal[2].num1);
cal[2].num2=simpl(cal[2].num2);
myprintf(cal[2].num1,cal[2].num2,1);
printf("\n");


}
int main()
{
struct data cal[3];
for(int i=0;i<=1;i++){
scanf("%lf%lf",&cal[i].num1,&cal[i].num2);
}
for(int i=0;i<4;i++){
printf("(");
myprintf(cal[0].num1,cal[0].num2,0);
printf(")");
printf(" %c ",item[i]);
printf("(");
myprintf(cal[1].num1,cal[1].num2,0);
printf(") = ");
//printf(" = ",item[i]);
getresult(cal,i);
}
return 0;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×