[英]Why is a modulo operator (%) result implicitly cast to the left side rather than the right side in C#?
Take the following code: 请使用以下代码:
long longInteger = 42;
int normalInteger = 23;
object rem = longInteger % normalInteger;
If rem
is the remainder of longInteger / normalInteger
, shouldn't the remainder always be bounded by the smaller sized "int", the divisor? 如果
rem
是longInteger / normalInteger
的余数, longInteger / normalInteger
余数总是不应该被较小的“int”(除数)限制吗? Yet in C#, the above code results in rem
being a long
. 然而在C#中,上面的代码导致
rem
很long
。
Is it safe to convert rem
to int
without any loss of data? 将
rem
转换为int
而不丢失任何数据是否安全?
int remainder = Convert.ToInt32(rem);
There is no overload of the modulo operator that takes a long
and an int
, so the int
will be converted to long
to match the other operand. 模数运算符没有带有
long
和int
重载,因此int
将转换为long
以匹配另一个操作数。
Looking at it at a lower level, in the CPU there is no separate instruction for calculating modulo, it's just one of the results of the division operation. 在较低级别查看它,在CPU中没有用于计算模数的单独指令,它只是除法运算的结果之一。 The output of the operation is the result of the division, and the reminder.
操作的输出是除法和提醒的结果。 Both are the same size, so as the result of the division has to be a
long
, so is the reminder. 两者都是相同的大小,因此除法的结果必须很
long
,提醒也是如此。
As the reminder has to be smaller than the divisor, you can safely cast the result to int
when the divisor comes from an int
. 由于提醒必须小于除数,因此当除数来自
int
时,可以安全地将结果转换为int
。
No matter what your two integers, the outcome must be lower than "normalInteger". 无论你的两个整数是什么,结果必须低于“normalInteger”。 Therefore, the result "rem" will be constrained to the limits of an int type.
因此,结果“rem”将被限制为int类型的限制。 So, it will be safe to convert rem to int without loss of data.
因此,在不丢失数据的情况下将rem转换为int是安全的。
yes it has not problem, the convert function is going to round the result. 是的,它没有问题,转换函数将围绕结果。 then you should know if it is usefull for you or not.
然后你应该知道它是否对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.