给变量起好名字,给函数写好注释,就不用多解释;
最小公倍数 = a × b / 最大公约数
大型项目需要文档,放过我吧:)
#include <stdio.h>
typedef struct fraction
{
long long molecule;
long long dinominator;
} Fraction;
Fraction add_fraction(Fraction, Fraction);
Fraction simplify_fraction(Fraction);
static long find_biggest_factor(long, long);
static long find_smallest_multiple(long, long);
void print_fraction(Fraction);
int main(void)
{
Fraction input;
Fraction sum = {0, 1};
int i;
int input_num;
scanf("%d", &input_num);
for (i = 0; i < input_num; i++)
{
scanf("%lld/%lld", &input.molecule, &input.dinominator);
sum = add_fraction(sum, input);
}
sum = simplify_fraction(sum);
print_fraction(sum);
return 0;
}
//input a/b c/d
//output x/y = a/b + c/d
Fraction add_fraction(Fraction a, Fraction b)
{
Fraction result;
long a_dinominator = a.dinominator;
long b_dinominator = b.dinominator;
long smallest_multiple = find_smallest_multiple(a_dinominator, b_dinominator);
result.molecule = a.molecule * (smallest_multiple / a_dinominator) + b.molecule * (smallest_multiple / b_dinominator);
result.dinominator = smallest_multiple;
return result;
}
//input a b
//output a * b / biggest_factor
static long find_smallest_multiple(long a, long b)
{
long biggest_factor = find_biggest_factor(a, b);
long smallest_multiple = a * b / biggest_factor;
return smallest_multiple;
}
//input a/b
//output (a/c)/(b/c) c is the biggest_factor
Fraction simplify_fraction(Fraction input)
{
Fraction result;
long biggest_factor = find_biggest_factor(input.molecule, input.dinominator);
result.molecule = input.molecule / biggest_factor;
result.dinominator = input.dinominator / biggest_factor;
return result;
}
//input a , b
//output c c is the biggest_factor of a and b
static long find_biggest_factor(long a, long b)
{
if (a == 0)
return b;
return find_biggest_factor(b % a, a);
}
//input | 3/2 | 2/1 | 3/7 |
//output | 1 1/2 | 2 | 3/7 |
void print_fraction(Fraction input)
{
long flag = input.molecule / input.dinominator;
if (input.molecule == 0)
//molecule is 0
{
printf("0");
}
else if (flag == 0)
//molecule < dimononator
{
printf("%lld/%lld", input.molecule, input.dinominator);
}
else if (flag * input.dinominator == input.molecule)
//molecule / dimonontor is integer
{
printf("%lld", input.molecule / input.dinominator);
}
else
//molecule / dimonontor isn't initeger
{
printf("%ld %lld/%lld", flag, input.molecule % input.dinominator, input.dinominator);
}
}