Why does the % operator sometimes output positive and sometimes negative?

≡放荡痞女 提交于 2021-01-27 13:48:28

问题


I was working on a script in unity when i realized something odd and after I finished the script I tested my realization in a visual studio console project.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(-3.5 % 1);
        Console.WriteLine(3.5 % (-1));
    }
}

The output was:

-0.5

0.5

Shouldn't the modulus operator give me -0.5 in both cases?


回答1:


Shouldn't the modulus operator give me -0.5 in both cases?

Why should it? Mathematically, both 0.5 and -0.5 are correct for the both cases.

-3.5 = -3 * 1 + (-0.5)
-3.5 = -4 * 1 + 0.5
3.5 = -3 * (-1) + 0.5
3.5 = -4 * (-1) + (-0.5)

Programmatically, it's defined by the C# language specification.

7.8.3 Remainder operator

Floating-point remainder:

float operator %(float x, float y);
double operator %(double x, double y); 

The following table lists the results of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s. In the table, x and y are positive finite values. z is the result of x % y and is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y. This method of computing the remainder is analogous to that used for integer operands, but differs from the IEEE 754 definition (in which n is the integer closest to x / y).

The table says that the sign of the remainder is the same as the sign of the first operand x.

In the case of -3.5 % 1:

x = 3.5
y = 1
n = 3
z = 3.5 - 3 * 1 = 0.5

According to the table, the result is -z, that is -0.5.

In the case of 3.5 % -1, x, y, n, z are the same as above. According to the table, the result is +z, that is 0.5.




回答2:


C#'s % operator is actually a remainder -- so it simply returns what's left over from the division. The most important part of that is that the remainder is only affected by the sign of the numerator, and not the divisor.

In the case of 3.5 positive, the 3 will divide perfectly, with 0.5 left over -- with -3.5, -3 will divide perfectly, with -0.5 left over. Whether you divide by -1 or 1 doesn't affect the outcome in either case, the remainder will be the same, and is only affected by the sign of the number itself.



来源:https://stackoverflow.com/questions/42661964/why-does-the-operator-sometimes-output-positive-and-sometimes-negative

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!