如何简化分数?
如何简化C#中的分数? 例如,给定1 11/6
,我需要将其简化为2 5/6
。
如果你想要的只是将你的分数变成一个混合数,其小数部分是一个适当的分数,就像前面给出的答案一样,你只需要在数字的整个部分加上numerator / denominator
,并将numerator / denominator
设置为numerator % denominator
。 使用循环完全没必要。
然而,术语“简化”通常是指将分数减少到其最低项。 你的例子并不清楚你是否也想要那个,因为这个例子是最低的两种方式。
这是一个C#类,它对一个混合数进行归一化,这样每个数字只有一个表示:小数部分始终是正确的,总是在最低的条件下,分母总是正的,整个部分的符号总是与分子的标志。
using System; public class MixedNumber { public MixedNumber(int wholePart, int num, int denom) { WholePart = wholePart; Numerator = num; Denominator = denom; Normalize(); } public int WholePart { get; private set; } public int Numerator { get; private set; } public int Denominator { get; private set; } private int GCD(int a, int b) { while(b != 0) { int t = b; b = a % b; a = t; } return a; } private void Reduce(int x) { Numerator /= x; Denominator /= x; } private void Normalize() { // Add the whole part to the fraction so that we don't have to check its sign later Numerator += WholePart * Denominator; // Reduce the fraction to be in lowest terms Reduce(GCD(Numerator, Denominator)); // Make it so that the denominator is always positive Reduce(Math.Sign(Denominator)); // Turn num/denom into a proper fraction and add to wholePart appropriately WholePart = Numerator / Denominator; Numerator %= Denominator; } override public String ToString() { return String.Format("{0} {1}/{2}", WholePart, Numerator, Denominator); } }
样品用法:
csharp> new MixedNumber(1,11,6); 2 5/6 csharp> new MixedNumber(1,10,6); 2 2/3 csharp> new MixedNumber(-2,10,6); 0 -1/3 csharp> new MixedNumber(-1,-10,6); -2 -2/3
int unit = 1; int numerator = 11; int denominator = 6; while(numerator >= denominator) { numerator -= denominator; if(unit < 0) unit--; else unit++; }
然后用变量做任何你喜欢的事情。
请注意,这不是特别通用....特别是我怀疑它会与负数一起发挥好(编辑:现在可能会更好)
int num = 11; int denom = 6; int unit = 1; while (num >= denom) { num -= denom; unit++; }
对不起,我没有完全理解有关跟踪单位价值的部分。
为了简化6/11
的分数你会看到你是否可以得到两个大于1的相同数字并且除以。
所以
-
2,4,6,8,10,12
没有 -
1,3,6,9,12
没有 -
4,8
没有 -
5,10
没有 -
6,12
没有 -
7
没有 -
8
没有 -
9
没有。
不会是所有人的答案所以它已经是最简单的了。 没有更多的事要做。