简化C#中的分数
作者:互联网
我已经制作了一个添加和减去分数的控制台应用程序,我添加了一个简化的函数:
public static Numbers Add(Numbers n1, Numbers n2)
{
int den1;
int num1;
int num2;
int dsimp;
int nsimp;
int numtop;
num1 = n1.Numerator * n2.Denominator;
num2 = n2.Numerator * n1.Denominator;
den1 = n1.Denominator * n2.Denominator;
numtop = num2 + num1;
if (numtop == 0)
{
return new Numbers(0);
}
if (numtop % n1.Denominator == 0)
{
nsimp = numtop / n1.Denominator;
dsimp = den1 / n1.Denominator;
return new Numbers(nsimp, dsimp);
}
else
{
return new Numbers(numtop, den1);
}
}
当我输入1/2 4/8时,它完全按照我告诉它的方式简化它,但是,它给了我8/8.这需要简化为1/1.如何将它简化为已经简化到最低分数的部分?
解决方法:
将分子和分母除以分子和分母的GCD (greatest common divisor).
例如:
从12/8开始说. GCD是4.因此3/2.
标签:c,math,fractions,simplify 来源: https://codeday.me/bug/20190610/1209609.html