为什么在 C# 中模运算符 (%) 结果隐式转换为左侧而不是右侧?

发布于 2024-10-18 00:07:56 字数 405 浏览 6 评论 0原文

采取以下代码:

long longInteger = 42;
int normalInteger = 23;
object rem = longInteger % normalInteger;

如果remlongInteger/normalInteger的余数,那么余数不应该总是以较小的“int”(除数)为界吗?但在 C# 中,上述代码会导致 remlong

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

肤浅与狂妄 2024-10-25 00:07:56

接受 longint 的模运算符没有重载,因此 int 将转换为 long 来匹配另一个操作数。

从较低的层面来看,CPU 中没有单独的求模指令,它只是除法运算的结果之一。运算的输出是除法的结果,以及提醒。两者的大小相同,因此除法的结果必须是long,因此提醒也是如此。

由于提醒必须小于除数,因此当除数来自 int 时,您可以安全地将结果转换为 int

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.

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 an int.

烟雨凡馨 2024-10-25 00:07:56

无论您的两个整数是什么,结果都必须低于“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.

撕心裂肺的伤痛 2024-10-25 00:07:56

是的,没有问题,转换函数将对结果进行四舍五入。那么你应该知道它对你是否有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文