#include <stdio.h>
#include <math.h>
struct rational
{
int numerator,denominator;
};
int get_numerator(struct rational a)
{
return a.numerator;
}
int get_denominator(struct rational a)
{
return a.denominator;
}
struct rational make_rational(int a,int b)
{
struct rational z;
z.numerator=a;
z.denominator=b;
return z;
}
int gcd(int a,int b)
{
int Max=a,Min=b;
if(a<b)
{
Max=b;
Min=a;
}
if(!(Max%Min))
return Min;
else
return gcd(Min,Max%Min);
}
struct rational regulation_rational(struct rational a)
{
int g=1;
if(!a.numerator)
return a;
if(a.denominator<0)
{
a.numerator=-a.numerator;
a.denominator=-a.denominator;
}
g=gcd(abs(a.numerator),abs(a.denominator));
a.numerator=a.numerator/g;
a.denominator=a.denominator/g;
return a;
}
struct rational add_rational(struct rational a,struct rational b)
{
struct rational z;
z.numerator=a.numerator*b.denominator+b.numerator*a.denominator;
z.denominator=a.denominator*b.denominator;
return regulation_rational(z);
}
struct rational sub_rational(struct rational a,struct rational b)
{
b.numerator=-b.numerator;
return regulation_rational(add_rational(a,b));
}
struct rational mul_rational(struct rational a,struct rational b)
{
struct rational z;
z.numerator=a.numerator*b.numerator;
z.denominator=a.denominator*b.denominator;
return regulation_rational(z);
}
struct rational div_rational(struct rational a,struct rational b)
{
struct rational z;
z.numerator=a.numerator*b.denominator;
z.denominator=b.numerator*a.denominator;
return regulation_rational(z);
}
//打印之前需要最简化分数
void print_rational(struct rational a)
{
if((!a.numerator)||(a.denominator==1))
printf("%d\n",a.numerator);
else
printf("%d/%d\n",a.numerator,a.denominator);
}
int main(void)
{
struct rational a = make_rational(1, 8); /* a=1/8 */
struct rational b = make_rational(-1, 8); /* b=-1/8 */
print_rational(add_rational(a, b));
print_rational(sub_rational(a, b));
print_rational(mul_rational(a, b));
print_rational(div_rational(a, b));
return 0;
}
|