整数乘法表现奇怪

Integer multiplication acting strange

我正在写分数 class,我想将双精度数转换为分数。我通过将 double 增加一个比例因子 10 直到它是一个整数然后将该比例因子作为分数的分母来做到这一点

我的问题是比例因子是一个整数,只能是 10 的倍数,例如 100 或 10000,但我得到的值离它很远。

public static Fraction ToFraction(double number)
{
    Fraction fraction = new Fraction();
    double tempNumber = number;
    int multiplier = 1;

    //Makes decimal to whole number and then sets the scaling to be the denominator
    //1.03 => 10.3 => 103 thus fraction = 103/100
    while (!(tempNumber % 1 == 0))
    {
        tempNumber *= 10;
        multiplier *= 10;
    }

    fraction.numerator = ((long)tempNumber);
    fraction.denominator = multiplier;

    return fraction;
}

我试图用 0.5154812884 做一个分数,作为测试,这意味着我应该得到分数 5,154,812,884 / 10,000,000,000 但它 returns 5,154,812,884/1,410,065,408

我尝试搜索,但找不到有类似问题的人

我在调试中包含了一些图片,其中显示了双精度输入以及生成的分子(分子)和分母(乘数) Number used for testing

Resulting fraction where tempNumber is right but multiplier is wrong

我认为您的问题是分母是 32 位整数。这是有道理的,因为 10,000,000,000 在 32 位 int 中溢出,return 的结果约为 1,410,065,412。考虑改变这一点。

double tempNumber = number;
long multiplier = 1;

编辑:您收到的分母结果我也能够在测试中收到并将乘数(用于确定分母)更改为长期固定的结果。