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。我如何才能将已经简化到尽可能低的分数简化?
I have made a console app that adds and subtracts fractions, I have added a function to simplify:
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);
}
}
When I put in 1/2 + 4/8 it simplifies it all perfectly the way I tell it to, but, it gives me 8/8. This needs to be simplified to 1/1. How do I get it to simplify what has already been simplified to the lowest possible fraction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将分子和分母除以分子和分母的GCD(最大公约数)。
例如:
从 12/8 开始。 GCD 是 4。因此是 3/2。
Divide the numerator and denominator by the GCD (greatest common divisor) of the numerator and denominator.
Eg:
Start with say 12/8. The GCD is 4. Thus 3/2.