为什么在 C# 中模运算符 (%) 结果隐式转换为左侧而不是右侧?
采取以下代码:
long longInteger = 42;
int normalInteger = 23;
object rem = longInteger % normalInteger;
如果rem
是longInteger/normalInteger
的余数,那么余数不应该总是以较小的“int”(除数)为界吗?但在 C# 中,上述代码会导致 rem
为 long
。
将 rem
转换为 int
是否安全且不会丢失任何数据?
int remainder = Convert.ToInt32(rem);
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? Yet in C#, the above code results in rem
being a long
.
Is it safe to convert rem
to int
without any loss of data?
int remainder = Convert.ToInt32(rem);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
接受
long
和int
的模运算符没有重载,因此int
将转换为long 来匹配另一个操作数。
从较低的层面来看,CPU 中没有单独的求模指令,它只是除法运算的结果之一。运算的输出是除法的结果,以及提醒。两者的大小相同,因此除法的结果必须是
long
,因此提醒也是如此。由于提醒必须小于除数,因此当除数来自
int
时,您可以安全地将结果转换为int
。There is no overload of the modulo operator that takes a
long
and anint
, so theint
will be converted tolong
to match the other operand.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. 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.As the reminder has to be smaller than the divisor, you can safely cast the result to
int
when the divisor comes from anint
.无论您的两个整数是什么,结果都必须低于“normalInteger”。因此,结果“rem”将受到 int 类型的限制。因此,将 rem 转换为 int 是安全的,不会丢失数据。
No matter what your two integers, the outcome must be lower than "normalInteger". Therefore, the result "rem" will be constrained to the limits of an int type. So, it will be safe to convert rem to int without loss of data.
是的,没有问题,转换函数将对结果进行四舍五入。那么你应该知道它对你是否有用。
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.