写在前面
- 实现思路
- 问题点
- 分子为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
分子 / 分母
fractional part
小数部分
测试用例
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;
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
{
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;
}