完整的C程序:
#include "stdio.h"
/* 分数结构 */
typedef struct
{
int numerator; /* 分子 */
int denominator; /* 分母 */
} Fraction;
int GCD(int a,int b);
int LCM(int a,int b);
Fraction Add(Fraction f1, Fraction f2);
void main()
{
Fraction f1, f2, f3;
f1.numerator = 1;
f1.denominator = 3;
f2.numerator = 1;
f2.denominator = 6;
f3 = Add(f1, f2);
printf("%d/%d + %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, f3.numerator, f3.denominator);
}
/* 返回两个分数相加的结果 */
Fraction Add(Fraction f1, Fraction f2)
{
Fraction retValue;
int lcm = LCM(f1.denominator, f2.denominator); /* 计算最小公倍数 */
int gcd;
retValue.denominator = lcm;
retValue.numerator = f1.numerator * lcm / f1.denominator + f2.numerator * lcm / f2.denominator;
gcd = GCD(retValue.numerator, retValue.denominator);
retValue.numerator /= gcd;
retValue.denominator /= gcd;
return retValue;
}
/* 返回两个整数的最大公约数 */
int GCD(int a,int b)
{
int i,temp_gcd;
for(i=a;i>=1;i--)
{
if(a%i==0)
{
if(b%i==0)
{
temp_gcd=i;
return temp_gcd;
}
}
}
}
/* 返回两个整数的最小公倍数 */
int LCM(int a,int b)
{
int temp_lcm;
temp_lcm = a * b / GCD(a,b);
return temp_lcm;
}
运行测试:
看看这个符合你的要求吗,运行没什么问题,不过可能有些麻烦
#include
main()
{
int nNume_1 = 0;
int nDeno_1 = 0;
int nNume_2 = 0;
int nDeno_2 = 0;
int nNume = 0;
int nDeno = 0;
int nNumeTmp = 0;
int nDenoTmp = 0;
int nComdiv = 0;
int nSmall = 0;
int nTmp = 0;
printf("Num 1:");
scanf("%d/%d", &nNume_1, &nDeno_1);
printf("Num 2:");
scanf("%d/%d", &nNume_2, &nDeno_2);
//计算相加
if(nDeno_1 == nDeno_2)
{
nNume = nNume_1 + nNume_2;
nDeno = nDeno_1;
}
else
{
nDeno = nDeno_1 * nDeno_2;//分母
nNume_1 = nNume_1 * nDeno_2;
nNume_2 = nNume_2 * nDeno_1;
nNume = nNume_1 + nNume_2;//分子
}
//取最大公约数
if(nNume < 0)//对负数进行处理
{
nNumeTmp = -nNume;
}
else
{
nNumeTmp = nNume;
}
nDenoTmp = nDeno;
//判断分子分母哪个绝对值大
if(nNumeTmp > nDenoTmp)
{
nComdiv = nNumeTmp;
nSmall = nDenoTmp;
}
else if(nNumeTmp < nDenoTmp)
{
nComdiv = nDenoTmp;
nSmall = nNumeTmp;
}
if(nNumeTmp != nDenoTmp)
{
//应用辗转相除法
while(nSmall > 0)//余数大于零(在循环最后原来的除数被赋值为余数了)
//循环之后nDenoTmp中记录了分子分母的最大公约数
{
nTmp = nComdiv % nSmall;
if(1 == nTmp)//最大公约数为1
{
nComdiv = 1;
break;
}
nComdiv = nSmall;
nSmall = nTmp;
}
nNume = nNume / nComdiv;
nDeno = nDeno / nComdiv;
printf("%d/%d\n", nNume, nDeno);
}
else
{
printf("1\n");
}
}