为什么 % 运算符有时输出正数有时输出负数? [英] Why does the % operator sometimes output positive and sometimes negative?
问题描述
当我发现一些奇怪的东西时,我正在统一编写脚本,完成脚本后,我在一个 Visual Studio 控制台项目中测试了我的实现.
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));
}
}
输出是:
-0.5
0.5
模数运算符不应该在两种情况下都给我 -0.5 吗?
Shouldn't the modulus operator give me -0.5 in both cases?
推荐答案
模数运算符不应该在两种情况下都给我 -0.5 吗?
Shouldn't the modulus operator give me -0.5 in both cases?
为什么要这样做?从数学上讲,这两种情况的 0.5 和 -0.5 都是正确的.
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)
以编程方式,它由 C# 语言规范定义.
Programmatically, it's defined by the C# language specification.
7.8.3 余数运算符
7.8.3 Remainder operator
浮点余数:
float operator %(float x, float y);
double operator %(double x, double y);
下表列出了所有可能组合的结果非零有限值、零、无穷大和 NaN.在表中,xy 是正的有限值.z 是 x % y 的结果,并且是计算为 x – n * y,其中 n 是最大的可能整数,即小于或等于 x/y.这种计算余数的方法是类似于用于整数操作数的,但不同于 IEEE754 定义(其中 n 是最接近 x/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).
该表表示余数的符号与第一个操作数 x 的符号相同.
The table says that the sign of the remainder is the same as the sign of the first operand x.
在-3.5 % 1
的情况下:
x = 3.5
y = 1
n = 3
z = 3.5 - 3 * 1 = 0.5
根据表格,结果是-z
,即-0.5.
According to the table, the result is -z
, that is -0.5.
在3.5 % -1
、x
、y
、n
、z的情况下
同上.根据表格,结果是+z
,即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.
这篇关于为什么 % 运算符有时输出正数有时输出负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!