写在前面

  • 实现思路
  • 最大公约数
  • 分数约分函数
  • 分数求和函数
  • 结果打印函数
  • 问题点
  • 分子为0、负数处理。
  • ​If there is a negative number, then the sign must appear in front of the numerator.​
  • ​You must output only the fractional part if the integer part is 0.​
  • 数据类型,范围溢出
  • 每步计算、每步约分
  • 计算最大公约数,注意计算分子、分母绝对值的公约数
  • 题目简单,20分钟a题
  • 英文单词
Rational Sum
有理数求和

numerator / denominator
分子 /

测试用例

input:
5
2/5 4/15 1/30 -2/60 8/3
output:
3 1/3

input:
2
4/3 2/3
output:
2

input:
3
1/3 -1/6 1/8
output:
7/24

ac代码

#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;

// 求a、b最大公约数
ll gcd(ll a, ll b)
{
return b==0 ? a : gcd(b, a%b);
}
// 分数,分子、分母
struct Fraction
{
ll up, down;
};
Fraction reduction(Fraction result)
{
// 分母为负,分子和分母取相反数
if(result.down < 0)
{
result.up = -result.up;
result.down = -result.down;
}

if(result.up == 0)
result.down = 1;
else
{
// 分子不为0,进行约分。分子、分母最大公约数
int d = gcd(abs(result.up), abs(result.down));
result.up/=d;
result.down /= d;
}
return result;
}

Fraction add(Fraction f1, Fraction f2)
{
Fraction result;
result.up = f1.up*f2.down + f2.up*f1.down;
result.down = f1.down*f2.down;
return reduction(result);
}

void showResult(Fraction r)
{
reduction(r);
if(r.down == 1)
printf("%lld\n", r.up);
else if(abs(r.up) > r.down)
printf("%lld %lld/%lld\n", r.up/r.down, abs(r.up)%r.down, r.down);
else
printf("%lld/%lld\n", r.up, r.down);
}

int main()
{
int n;
scanf("%d", &n);

Fraction sum, tmp;
sum.up = 0;
sum.down = 1;
for(int i=0; i<n; i++)
{
scanf("%lld/%lld", &tmp.up, &tmp.down);
sum = add(sum, tmp);
}

showResult(sum);
return 0;
}

学习代码

  • 参考
#include <iostream>
#include <cstdlib>
using namespace std;
long long gcd(long long a, long long b) {return b == 0 ? abs(a) : gcd(b, a % b);}
int main() {
long long n, a, b, suma = 0, sumb = 1, gcdvalue;
scanf("%lld", &n);
for(int i = 0; i < n; i++) {
scanf("%lld/%lld", &a, &b);
gcdvalue = gcd(a, b);
a = a / gcdvalue;
b = b / gcdvalue;
suma = a * sumb + suma * b;
sumb = b * sumb;
gcdvalue = gcd(suma, sumb);
sumb = sumb / gcdvalue;
suma = suma / gcdvalue;
}
long long integer = suma / sumb;
suma = suma - (sumb * integer);
if(integer != 0) {
printf("%lld", integer);
if(suma != 0) printf(" ");
}
if(suma != 0)
printf("%lld/%lld", suma, sumb);
if(integer == 0 && suma == 0)
printf("0");
return 0;
}