如何在c#中添加两个分数,如下所示:
11/6 + 3/4 = 31/12
然后你会如何简化答案?
答案 0 :(得分:6)
由于周五晚上的无聊打击......导致了一个操作过载的Fraction类。设计的清醒无法得到保证。
就像这样......
Fraction left = "1/2";
Fraction right = "3/8";
Fraction result1 = ((left + right) * left / right).Simplify();
Console.WriteLine(result1);
Fraction test2 = "12/32";
test2 = test2.Simplify();
Console.WriteLine(test2);
如下所示的实施......
public struct Fraction
{
public int Numerator { get; set; }
public int Denominator { get; set; }
public Fraction(int numerator, int denominator)
: this()
{
Numerator = numerator;
Denominator = denominator;
}
public Fraction Simplify()
{
int gcd = GCD();
return new Fraction(Numerator / gcd, Denominator / gcd);
}
public Fraction InTermsOf(Fraction other)
{
return Denominator == other.Denominator ? this :
new Fraction(Numerator * other.Denominator, Denominator * other.Denominator);
}
public int GCD()
{
int a = Numerator;
int b = Denominator;
while (b != 0)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
public Fraction Reciprocal()
{
return new Fraction(Denominator, Numerator);
}
public static Fraction operator +(Fraction left, Fraction right)
{
var left2 = left.InTermsOf(right);
var right2 = right.InTermsOf(left);
return new Fraction(left2.Numerator + right2.Numerator, left2.Denominator);
}
public static Fraction operator -(Fraction left, Fraction right)
{
var left2 = left.InTermsOf(right);
var right2 = right.InTermsOf(left);
return new Fraction(left2.Numerator - right2.Numerator, left2.Denominator);
}
public static Fraction operator *(Fraction left, Fraction right)
{
return new Fraction(left.Numerator * right.Numerator, left.Denominator * right.Denominator);
}
public static Fraction operator /(Fraction left, Fraction right)
{
return new Fraction(left.Numerator * right.Denominator, left.Denominator * right.Numerator);
}
public static implicit operator Fraction(string value)
{
var tokens = value.Split('/');
int num;
int den;
if (tokens.Length == 1 && int.TryParse(tokens[0], out num))
{
return new Fraction(num, 1);
}
else if (tokens.Length == 2 && int.TryParse(tokens[0], out num) && int.TryParse(tokens[1], out den))
{
return new Fraction(num, den);
}
throw new Exception("Invalid fraction format");
}
public override string ToString()
{
return string.Format("{0}/{1}", Numerator, Denominator);
}
}
答案 1 :(得分:3)
.Net没有Rational Numbers的内置支持(我知道),但是至少有一个现有的库。
你的解决方案最终将归结为存储分子和分母(可能在你创建的自定义类中),对其他分子/分母对(可能是你班上的implementing overloaded operators)进行算术运算,并应用分数简化算法。
以下是一些资源:
现有实施
减少分数的方法
答案 2 :(得分:2)
首先找到LCD,然后执行以下操作
num1 *= lcd / denum1;
num2 *= lcd / denum2;
sumNum = num1 + num2;
答案 3 :(得分:0)
我从未使用过c#,但我可以解释一下如何做到这一点。