为什么 % 运算符有时输出正数有时输出负数?
Why does the % operator sometimes output positive and sometimes negative?
当我意识到一些奇怪的事情时,我正在统一编写脚本,在完成脚本后,我在 visual studio 控制台项目中测试了我的实现。
class Program
{
static void Main(string[] args)
{
Console.WriteLine(-3.5 % 1);
Console.WriteLine(3.5 % (-1));
}
}
输出是:
-0.5
0.5
模数运算符不应该在两种情况下都给我 -0.5 吗?
C# 的 % 运算符实际上是一个余数——所以它只是 returns 除法的剩余部分。其中最重要的部分是余数仅受分子符号的影响,而不受除数的影响。
在 3.5 为正数的情况下,3 将完全除以,还剩下 0.5 -- 如果是 -3.5,-3 将完全除以,还剩下 -0.5。无论您除以 -1 还是 1 都不会影响结果,余数将相同,并且仅受数字本身符号的影响。
Shouldn't the modulus operator give me -0.5 in both cases?
为什么要这样做?从数学上讲,0.5 和 -0.5 对于这两种情况都是正确的。
-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# 语言规范定义。
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).
table表示余数的符号与第一个操作数x的符号相同。
在-3.5 % 1
的情况下:
x = 3.5
y = 1
n = 3
z = 3.5 - 3 * 1 = 0.5
根据table,结果是-z
,即-0.5。
3.5 % -1
、x
、y
、n
、z
同上。根据table,结果是+z
,即0.5.
当我意识到一些奇怪的事情时,我正在统一编写脚本,在完成脚本后,我在 visual studio 控制台项目中测试了我的实现。
class Program
{
static void Main(string[] args)
{
Console.WriteLine(-3.5 % 1);
Console.WriteLine(3.5 % (-1));
}
}
输出是:
-0.5
0.5
模数运算符不应该在两种情况下都给我 -0.5 吗?
C# 的 % 运算符实际上是一个余数——所以它只是 returns 除法的剩余部分。其中最重要的部分是余数仅受分子符号的影响,而不受除数的影响。
在 3.5 为正数的情况下,3 将完全除以,还剩下 0.5 -- 如果是 -3.5,-3 将完全除以,还剩下 -0.5。无论您除以 -1 还是 1 都不会影响结果,余数将相同,并且仅受数字本身符号的影响。
Shouldn't the modulus operator give me -0.5 in both cases?
为什么要这样做?从数学上讲,0.5 和 -0.5 对于这两种情况都是正确的。
-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# 语言规范定义。
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).
table表示余数的符号与第一个操作数x的符号相同。
在-3.5 % 1
的情况下:
x = 3.5
y = 1
n = 3
z = 3.5 - 3 * 1 = 0.5
根据table,结果是-z
,即-0.5。
3.5 % -1
、x
、y
、n
、z
同上。根据table,结果是+z
,即0.5.