我有一个特定的案例,我需要返回'粗俗'尽可能分数。我提出的代码如下
var complexFractionString = heaveValue.ToComplexFractionString();
complexFractionString = complexFractionString.Replace("1/8", "⅛");
complexFractionString = complexFractionString.Replace("1/4", "¼");
complexFractionString = complexFractionString.Replace("3/8", "⅜");
complexFractionString = complexFractionString.Replace("1/2", "½");
complexFractionString = complexFractionString.Replace("5/8", "⅝");
complexFractionString = complexFractionString.Replace("3/4", "¾");
complexFractionString = complexFractionString.Replace("7/8", "⅞");
return complexFractionString;
.ToComplexFractionString()是一种以字符串格式返回double的最小公分母分数的方法。即.5的输入将返回" 1/2"
此代码现在适用于我的用例,但我不喜欢它的结构。它是非常脆弱的,只有一小部分是" 1/16"或" 1/32"没有被改变就能通过,代码是一堆线来做一些应该相对容易的事情。
在C#中有更好的方法吗?
答案 0 :(得分:2)
卢克,使用武力(不可变结构)。
public struct Fraction
{
readonly int numerator, denominator;
public Fraction(double x)
{
// construct a fraction
}
public Fraction(int numerator, int denominator)
{
this.numerator=numerator;
this.denominator=denominator;
}
public Fraction Reduced() { /* Simplify */ }
public override string ToString()
{
return GetVulgarFraction(numerator, denominator);
}
static string GetVulgarFraction(int numerator, int denominator)
{
if(numerator<0)
{
// Handle -1/2 as "-½"
return string.Format("-{0}",
GetVulgarFraction(-numerator, denominator));
}
if(numerator>denominator)
{
// Handle 7/4 as "1 ¾"
return string.Format("{0} {1}",
numerator/denominator,
GetVulgarFraction(numerator%denominator, denominator));
}
// Handle 0/1 = "0"
if(numerator==0) return "0";
// Handle 10/1 = "10"
if(denominator==1) return numerator.ToString();
// Handle 1/2 = ½
if(denominator==2)
{
if(numerator==1) return "½";
}
// Handle 1/4 = ¼
if(denominator==4)
{
if(numerator==1) return "¼";
if(numerator==3) return "¾";
}
// Handle 1/8 = ⅛
if(denominator==8)
{
if(numerator==1) return "⅛";
if(numerator==3) return "⅜";
if(numerator==5) return "⅝";
if(numerator==7) return "⅞";
}
// Catch all
return string.Format("{0}/{1}", numerator, denominator);
}
}