c语⾔编程实现两个分数相加,C语⾔分数相加
完整的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;
}
完整的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;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论