VB.NET 与 C# 整数除法
有人愿意解释为什么这两段代码表现出不同的结果吗?
VB.NET v4.0
Dim p As Integer = 16
Dim i As Integer = 10
Dim y As Integer = p / i
//Result: 2
C# v4.0
int p = 16;
int i = 10;
int y = p / i;
//Result: 1
Anyone care to explain why these two pieces of code exhibit different results?
VB.NET v4.0
Dim p As Integer = 16
Dim i As Integer = 10
Dim y As Integer = p / i
//Result: 2
C# v4.0
int p = 16;
int i = 10;
int y = p / i;
//Result: 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您查看这两个片段生成的 IL 代码时,您会发现 VB.NET 首先将整数值转换为双精度数,应用除法,然后对结果进行舍入,然后将结果转换回 int32 并存储在 y 中。
C# 没有做这些。
VB.NET IL 代码:
C# IL 代码:
VB 中的“正确”整数除法需要一个反斜杠:p \ i
When you look at the IL-code that those two snippets produce, you'll realize that VB.NET first converts the integer values to doubles, applies the division and then rounds the result before it's converted back to int32 and stored in y.
C# does none of that.
VB.NET IL Code:
C# IL Code:
The "proper" integer division in VB needs a backwards slash: p \ i
在 VB 中,要进行整数除法,请反转斜杠:
否则它会扩展为浮点数进行除法,然后强制返回
int
分配给y
时进行四舍五入。In VB, to do integer division, reverse the slash:
otherwise it is expanded to floating-point for the division, then forced back to an
int
after rounding when assigned toy
.VB.NET 整数除法运算符是
\
,而不是/。
VB.NET integer division operator is
\
, not/
.“C# 和 VB 中的除法执行方式不同。与其他基于 C 的语言一样,当两个操作数都是整数文字或整数变量(或整数常量)时,C# 会截断除法结果。在 VB 中,必须使用整数除法运算符 (
\
) 以获得类似的结果。”来源
"Division is performed differently in C# and VB. C#, like other C-based languages truncates the division result when both operands are integer literals or integer variables (or integer constants). In VB, you must use the integer division operator (
\
) to get a similar result."Source
在 C# 中,当分子和分母都是整数时,使用
/
进行整数除法。然而,在 VB.Net 中“/”会导致浮点除法,因此对于 VB.Net 中的整数除法,请使用\
。请查看此 MSDN 帖子。In C#, integer division is applied with
/
when both numerator and denomenator are integers. Whereas, in VB.Net '/' results in floating point divsion, so for integer division in VB.Net use\
. Have a look at this MSDN post.