如果你想要的只是将你的分数变成一个混合数,其小数部分是一个合适的分数,就像前面给出的答案一样,你只需要加上数字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);
}
}
Run Code Online (Sandbox Code Playgroud)
样品用法:
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
Run Code Online (Sandbox Code Playgroud)
int num = 11;
int denom = 6;
int unit = 1;
while (num >= denom)
{
num -= denom;
unit++;
}
Run Code Online (Sandbox Code Playgroud)
抱歉,我没有完全理解有关跟踪单位值的部分。
| 归档时间: |
|
| 查看次数: |
8185 次 |
| 最近记录: |