Example_1

任务: 分数计算器(分数加减乘除运算)

步骤:

​ 1.加减法首先要用到通分,要寻找最小公倍数的函数。

​ 2.最小公倍数可以用最大公约数来求,辗转相减法或辗转相除法。

​ 3.计算完后需要涉及到约分。

代码实现

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
95
96
97
98
99
100
101
102
103
104
105
106
107
//1.最大公约数
int find_Gcd(int a, int b) //Greate common divisor
{
if (a == b)
return a;

else
{
if (a < b)
{
int c = b;
b = a;
a = c;

}
return a - b > b ? find_Gcd(a - b, b) : find_Gcd(b, a - b);
}
}

//2.最小公倍数
int Lcm(int a, int b) //Least common multiple
{
return a * b / find_Gcd(a, b);
}

//3.约分
void yuefen(int& a, int& b) // a/b的约分
{
int i = find_Gcd(a, b);

a = a / i;

b = b / i;

}


//4.四则运算
void add(int a, int b, int c, int d)
{
printf("%d/%d + %d/%d = ", a, b, c, d);
int n = Lcm(b, d);
int i = n / b;
int j = n / d;
a = a * i;
c = c * j;
int s = a + c;
yuefen(s, d);
printf("%d/%d\n", s, d);

}

void sub(int a, int b, int c, int d)
{
printf("%d/%d - %d/%d = ", a, b, c, d);
int n = Lcm(b, d);
int i = n / b;
int j = n / d;
a = a * i;
c = c * j;
int s = a - c;
yuefen(s, d);
printf("%d/%d\n", s, d);
}

void mul(int a, int b, int c, int d)
{
printf("%d/%d * %d/%d = ", a, b, c, d);
a = a * c;
b = b * d;
yuefen(a, b);
printf("%d/%d\n", a, b);
}

void div(int a, int b, int c, int d)
{
printf("%d/%d * %d/%d = ", a, b, c, d);
a = a * d;
b = b * c;
yuefen(a, b);
printf("%d/%d\n", a, b);
}


//5.main函数
int main()
{
char op;
int a, b, c, d;
scanf("%d,%d,%c,%d,%d", &a, &b, &op, &c, &d);
switch (op)
{
case '+':
add(a, b, c, d);
break;
case '*':
mul(a, b, c, d);
break;
case '-':
sub(a, b, c, d);
break;
case '/':
div(a, b, c, d);
break;

}
}