PAT-A 1081,题目地址:https://www.patest.cn/contests/pat-a-practise/1081
这道题目不难,细心点别写错就好。
思路:
- 每输入一个分数,就往最终结果里加一个,不过此时还不急着化为假分数
- 等加完所有的数,在统一约分,化为假分数等等
注意:分数相加一般都要使得分母相乘,为了防止100个分数相加使得分母过大超出数据范围,建议每次加完都约分一下,但是结果不化为假分数。代码直接AC了,也不知道不进行约分会不会有case出错
代码如下:
#include <iostream>
using namespace std;
//计算出两个数a,b的最大公约数
int max_factor(int a, int b){
a = a < 0 ? -a : a;
b = b < 0 ? -b : b;
if(a > b){
int temp = a;
a = b;
b = temp;
}
for(int i = a; i >= 2; i--){
if(i > 0 && a % i == 0 && b % i == 0){
return i;
}
}
return 1;
}
class Number{
public:
int integer; //整数部分
int numrator; //分子
int deno; //分母
Number(): integer(0), numrator(0), deno(1){}
Number(int a, int b, int c): integer(a), numrator(b), deno(c){}
//化为假分数并约分
void change(){
integer = numrator / deno;
numrator %= deno;
int factor = max_factor(numrator, deno);
numrator /= factor;
deno /= factor;
}
//仅仅约分
void simple(){
int factor = max_factor(numrator, deno);
numrator /= factor;
deno /= factor;
}
};
//两个分数相加
Number add(const Number& a, const Number& b){
int deno = a.deno * b.deno;
int numrator = a.deno * b.numrator + a.numrator * b.deno;
if(deno < 0)
numrator = -numrator;
return Number(0, numrator, deno);
}
int main(){
int n;
scanf("%d", &n);
Number each;
Number all;
for(int i = 0; i < n; i++){
scanf("%d/%d", &each.numrator, &each.deno);
all = add(all, each); //输入一个,加一个
all.simple();
}
all.change();
if(all.integer == 0 && all.numrator == 0){
cout << "0" << endl;
}
else if(all.integer != 0 && all.numrator == 0){
cout << all.integer << endl;
}
else if(all.integer == 0 && all.numrator != 0){
cout << all.numrator << "/" << all.deno << endl;
}
else{
cout << all.integer << " " << all.numrator << "/" << all.deno << endl;
}
return 0;
}
网友评论