c#分数计算器有问题

c#分数计算器有问题,c#,C#,明天我有一个作业要交,必须用整数加减分数,我对所有这些数字都有点困惑,数学也帮不上忙 它正确地执行了数学运算,但它一直在为整个变量设置1,而它应该是0,我一辈子都不明白为什么 这是我的分数.cs: class Fraction { int num, den, whole, newnum; public Fraction(int numerator, int denominator, int whole = 0) { this.num = numerat

明天我有一个作业要交,必须用整数加减分数,我对所有这些数字都有点困惑,数学也帮不上忙


它正确地执行了数学运算,但它一直在为整个变量设置1,而它应该是0,我一辈子都不明白为什么

这是我的分数.cs:

class Fraction
{
    int num, den, whole, newnum;

    public Fraction(int numerator, int denominator, int whole = 0)
    {

        this.num = numerator;
        this.den = denominator;
        this.whole = whole;
    }

    public Fraction Add(Fraction other)
    {
        int temp1 = num, temp2 = den;
        if (Math.Abs(this.whole) > 0)
        {
            newnum = temp2 * whole;
            newnum = +temp1;
            temp1 = newnum;
        }
        if (Math.Abs(other.whole) > 0)
        {
            other.newnum = other.den * other.whole;
            other.newnum = +other.num;
            other.num = other.newnum;
        }
        temp1 = temp1 * other.den + temp2 * other.num;
        temp2 = temp2 * other.den;
        if (temp1 == temp2 || temp1 > temp2)
        {
            whole = temp1 / temp2;
            temp1 = temp1 % temp2;
        }

        Fraction newFrac = new Fraction(temp1, temp2, whole);
        return newFrac;
    }
}
在我的Program.cs中,这是我的测试:

Fraction fra1 = new Fraction(1, 2);
Fraction fra2 = new Fraction(3, 4, 1);
Fraction fra3 = fra1.Add(fra2);
Console.WriteLine("Fraction 1: " + fra1);
Console.WriteLine("Fraction 2: " + fra2);
Console.WriteLine("{0} + {1} = {2}", fra1, fra2, fra3);
以下是我目前得到的结果:

任何帮助都将不胜感激!提前谢谢。
奥斯汀

我认为你的问题在于这一行:

whole = temp1 / temp2
似乎您不小心修改了当前实例的
整体
值。这就是导致
fra1
1/2
1/2
发生“神奇”变化的原因。使用一个临时变量可以解决问题,但我也建议进行类似的调整,以避免意外地修改
other
的字段,并删除
newnum
字段,该字段显然只是用于计算的临时占位符


如果您想使这个类不可变,我还建议您设置每个字段以避免这些错误

“它正确地完成了数学运算”-但事实并非如此。1/2 + 7/4 != 5/4,这是你的程序吐出来的。看起来你几乎在尝试减法
1 3/4-1 1/2
等于
2/8
@SamIam,除了第一个数字应该是1/2。根据p.s.w.g的回答,它只是在
Add()
的末尾被无意中更改了。一旦修复了该错误,您可能可以在代码复查堆栈交换站点上发布工作版本。你可以得到很多关于如何更干净地写这样的东西的建议