VB.NET 中的除法
VB.NET 中的除法 /
和 \
有什么区别?
我的代码根据我使用的代码给出了非常不同的答案。我以前见过这两种,但我一直不知道有什么区别。
What's the difference between /
and \
for division in VB.NET?
My code gives very different answers depending on which I use. I've seen both before, but I never knew the difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有两种除法。快法和慢法。许多编译器试图诱骗您以更快的方式完成此操作。 C# 就是其中之一,试试这个:
输出:0
您对这个结果满意吗?当表达式的左侧和右侧都是整数时,这是技术上正确的、记录的行为。这会进行快速的整数除法。处理器上的 IDIV 指令,而不是(臭名昭著的)FDIV 指令。也与所有花括号语言的工作方式完全一致。但绝对是 SO 中“发生了什么事”问题的主要来源。为了获得满意的结果,您必须执行以下操作:
输出:0.5
左侧现在是双精度型,强制进行浮点除法。计算器显示的结果类型。调用 FDIV 的其他方法是将右侧设为浮点数或将操作数之一显式转换为 (double)。
VB.NET 不是这样工作的,/ 运算符始终是浮点除法,无论类型如何。有时您确实想要整数除法。这就是
\
的作用。There are two ways to divide numbers. The fast way and the slow way. A lot of compilers try to trick you into doing it the fast way. C# is one of them, try this:
Output: 0
Are you happy with that outcome? It is technically correct, documented behavior when the left side and the right side of the expression are integers. That does a fast integer division. The IDIV instruction on the processor, instead of the (infamous) FDIV instruction. Also entirely consistent with the way all curly brace languages work. But definitely a major source of "wtf happened" questions at SO. To get the happy outcome you would have to do something like this:
Output: 0.5
The left side is now a double, forcing a floating point division. With the kind of result your calculator shows. Other ways to invoke FDIV is by making the right-side a floating point number or by explicitly casting one of the operands to (double).
VB.NET doesn't work that way, the / operator is always a floating point division, irrespective of the types. Sometimes you really do want an integer division. That's what
\
does.上述代码:
Code for the above: