VB.NET 中的整数除法舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17335582/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:03:16  来源:igfitidea点击:

Integer division rounding in VB.NET

vb.netvisual-studio-2010

提问by user2472706

When two variables are declared as integer type and you perform

当两个变量被声明为整数类型并且你执行

14/4, you get 4, but when you use integer division, 14\4, you get 3.

14/4,你得到 4,但是当你使用整数除法时,14\4,你得到 3。

I thought when you use integer division it rounds to the closest even number. So 14\4 = 3.5 (4 is the closest even number) should be 4 instead, right?

我认为当你使用整数除法时,它会四舍五入到最接近的偶数。所以 14\4 = 3.5(4 是最接近的偶数)应该是 4,对吧?

回答by fareed

In VB.NET, the /operator is defined to return a floating-point result. It converts the variables to double before performing the division.

在 VB.NET 中,/运算符被定义为返回一个浮点结果。它在执行除法之前将变量转换为 double。

This is not the case in the integer division \where the division is performed without the remainder if the quotient is a decimal (decimals are ignored). For example if the quotient is 3.x, then xis ignored

\如果商是小数(忽略小数),则在整数除法中不是这种情况,在整数除法中,除法没有余数。例如,如果商为3.x,则x忽略

回答by JLRishe

When you cast a floating point number to an integer in VB.NET, the value is rounded to the nearest even number. Apparently rounding a number when converting it to an integer is a behavior that stretches back to the days of the BASIC language.

当您在 VB.NET 中将浮点数转换为整数时,该值将四舍五入为最接近的偶数。显然,在将数字转换为整数时四舍五入是一种可以追溯到 BASIC 语言时代的行为。

However, when performing integer division (with the \operator), the fractional part is simply discarded, no matter what the fractional part is. This is why you get the behavior that you are seeing.

但是,在执行整数除法时(使用\运算符),无论小数部分是什么,小数部分都会被简单地丢弃。这就是为什么你会得到你所看到的行为。