vb.net VB.NET中的划分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4341611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Division in VB.NET
提问by Cyclone
What's the difference between /
and \
for division in VB.NET?
VB.NET 中的除法/
和\
除法有什么区别?
My code gives very different answers depending on which I use. I've seen both before, but I never knew the difference.
根据我使用的代码,我的代码给出了非常不同的答案。我以前都见过,但我从来不知道有什么区别。
回答by Hans Passant
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:
有两种划分数字的方法。快的方式和慢的方式。许多编译器试图欺骗您以快速的方式完成它。C# 就是其中之一,试试这个:
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine(1 / 2);
Console.ReadLine();
}
}
Output: 0
输出: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:
你对这个结果满意吗?当表达式的左侧和右侧是整数时,这是技术上正确的记录行为。这会进行快速整数除法。处理器上的 IDIV 指令,而不是(臭名昭著的)FDIV 指令。也完全符合所有花括号语言的工作方式。但绝对是 SO 上“wtf发生”问题的主要来源。要获得满意的结果,您必须执行以下操作:
Console.WriteLine(1.0 / 2);
Output: 0.5
输出: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).
左侧现在是一个双精度数,强制进行浮点除法。计算器显示的结果类型。调用 FDIV 的其他方法是将右侧设置为浮点数或将其中一个操作数显式转换为 (double)。
VB.NET doesn't work that way, the / operator is alwaysa floating point division, irrespective of the types. Sometimes you really dowant an integer division. That's what \
does.
VB.NET 不是这样工作的, / 运算符始终是浮点除法,无论类型如何。有时候,你真的做想的整数除法。这就是\
它的作用。
回答by neo2862
10 / 3 = 3.333
10 \ 3 = 3 (the remainder is ignored)
回答by Daniel A. White
/ Division
\ Integer Division
回答by adrianwadey
10 / 3 = 3.33333333333333, assigned to integer = 3
10 \ 3 = 3, assigned to integer = 3
20 / 3 = 6.66666666666667, assigned to integer = 7
20 \ 3 = 6, assigned to integer = 6
Code for the above:
以上代码:
Dim a, b, c, d As Integer
a = 10 / 3
b = 10 \ 3
c = 20 / 3
d = 20 \ 3
Debug.WriteLine("10 / 3 = " & 10 / 3 & ", assigned to integer = " & a)
Debug.WriteLine("10 \ 3 = " & 10 \ 3 & ", assigned to integer = " & b)
Debug.WriteLine("20 / 3 = " & 20 / 3 & ", assigned to integer = " & c)
Debug.WriteLine("20 \ 3 = " & 20 \ 3 & ", assigned to integer = " & d)