我试图通过找到最小的公分母然后相加来将两个粗俗的分数相加。但是,我的代码没有按预期运行,并且输出了两个非常高的负数。当我将第二个分数更改为 3/15 时,它输出 0/0。
这是我的主要程序代码:
class Program
{
static void Main(string[] args)
{
Fraction n = new Fraction(2, 4);
Fraction z = new Fraction(3, 12);
Fraction sum = n.Add(z, n);
int num = sum.Numerator;
int den = sum.Denominator;
Console.WriteLine("{0}/{1}", num, den);
Console.ReadKey(true);
}
}
这是我的Fraction
课程代码:
internal class Fraction
{
public Fraction(int numerator, int denominator)
{
Numerator = numerator;
Denominator = denominator;
}
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public Fraction Add(Fraction fraction2, Fraction fraction8)
{
int lcd = GetLCD(fraction8, fraction2);
int x = lcd/fraction8.Denominator;
int n = lcd/fraction2.Denominator;
int f2num = fraction2.Numerator*n;
int f8num = fraction8.Numerator*x;
int t = fraction2.Numerator;
Fraction Fraction3 = new Fraction(f2num+f8num,lcd);
return Fraction3;
}
public int GetLCD(Fraction b, Fraction c)
{
int i = b.Denominator;
int j = c.Denominator;
while (true)
{
if (i == j)
{
return i;
}
j = j + j;
i = i + i;
}
}
}