为什么 C# 中的整数除法返回整数而不是浮点数?

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

Why does integer division in C# return an integer and not a float?

c#division

提问by BanditoBunny

Does anyone know why integer division in C# returns an integer and not a float? What is the idea behind it? (Is it only a legacy of C/C++?)

有谁知道为什么 C# 中的整数除法返回整数而不是浮点数?它背后的想法是什么?(它只是 C/C++ 的遗产吗?)

In C#:

在 C# 中:

float x = 13 / 4;   
//== operator is overridden here to use epsilon compare
if (x == 3.0)
   print 'Hello world';

Result of this code would be:

此代码的结果将是:

'Hello world'

Strictly speaking, there is no such thing as integer division (division by definition is an operation which produces a rational number, integers are a very small subset of which.)

严格来说,没有整数除法这样的东西(根据定义,除法是产生有理数的运算,整数是其中的一个很小的子集。)

采纳答案by Servy

While it is common for new programmer to make this mistake of performing integer division when they actually meant to use floating point division, in actual practice integer division is a very common operation. If you are assuming that people rarely use it, and that every time you do division you'll always need to remember to cast to floating points, you are mistaken.

虽然新程序员在实际打算使用浮点除法时经常犯执行整数除法的错误,但实际上整数除法是一种非常常见的操作。如果您假设人们很少使用它,并且每次进行除法时您总是需要记住转换为浮点数,那么您就错了。

First off, integer division is quite a bit faster, so if you only need a whole number result, one would want to use the more efficient algorithm.

首先,整数除法要快得多,所以如果你只需要一个整数结果,人们会想要使用更有效的算法。

Secondly, there are a number of algorithms that use integer division, and if the result of division was always a floating point number you would be forced to round the result every time. One example off of the top of my head is changing the base of a number. Calculating each digit involves the integer division of a number along with the remainder, rather than the floating point division of the number.

其次,有许多算法使用整数除法,如果除法的结果总是一个浮点数,你将不得不每次都对结果进行四舍五入。我最想知道的一个例子是改变数字的基数。计算每个数字涉及数字的整数除法和余数,而不是数字的浮点除法。

Because of these (and other related) reasons, integer division results in an integer. If you want to get the floating point division of two integers you'll just need to remember to cast one to a double/float/decimal.

由于这些(和其他相关)原因,整数除法会产生整数。如果你想获得两个整数的浮点除法你只需要记住一个铸到double/ float/ decimal

回答by Sergey Berezovskiy

See C# specification. There are three types of division operators

请参阅 C#规范。除法运算符的三种类型

  • Integer division
  • Floating-point division
  • Decimal division
  • 整数除法
  • 浮点除法
  • 十进制除法

In your case we have Integer division, with following rules applied:

在您的情况下,我们有整数除法,应用以下规则:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

除法将结果向零舍入,结果的绝对值是小于两个操作数的商绝对值的最大可能整数。当两个操作数的符号相同时,结果为零或正数,当两个操作数的符号相反时,结果为零或负数。

I think the reason why C# use this type of division for integers (some languages return floating result) is hardware - integers division is faster and simpler.

我认为 C# 对整数使用这种类型的除法(某些语言返回浮点结果)的原因是硬件 - 整数除法更快更简单。

回答by CodeCaster

Since you don't use any suffix, the literals 13and 4are interpreted as integer:

由于您不使用任何后缀,因此文字134被解释为整数:

Manual:

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

手册:

如果文字没有后缀,则它具有可以表示其值的这些类型中的第一个:int, uint, long, ulong

Thus, since you declare 13as integer, integer division will be performed:

因此,由于您声明13为整数,因此将执行整数除法:

Manual:

For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The predefined division operators are listed below. The operators all compute the quotient of x and y.

Integer division:

int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);

手册:

对于 x / y 形式的运算,应用二元运算符重载解析来选择特定的运算符实现。操作数转换为所选运算符的参数类型,结果类型为运算符的返回类型。

下面列出了预定义的除法运算符。运算符都计算 x 和 y 的商。

整数除法:

int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);

And so rounding down occurs:

因此发生四舍五入:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

除法将结果向零舍入,结果的绝对值是小于两个操作数的商绝对值的最大可能整数。当两个操作数的符号相同时,结果为零或正数,当两个操作数的符号相反时,结果为零或负数。

If you do the following:

如果您执行以下操作:

int x = 13f / 4f;

You'll receive a compiler error, since a floating-point division (the /operator of 13f) results in a float, which cannot be cast to int implicitly.

您将收到编译器错误,因为浮点除法( 的/运算符13f)导致浮点数,不能隐式转换为 int 。

If you want the division to be a floating-point division, you'll have to make the result a float:

如果您希望除法是浮点除法,则必须使结果为浮点数:

float x = 13 / 4;

Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0. To explicitly declare the operands as float, using the fsuffix (13f, 4f).

请注意,您仍将除以整数,这些整数将隐式转换为浮点数:结果将为3.0. 使用f后缀 ( 13f, 4f)将操作数显式声明为浮点数。

回答by Steven Doggart

Each data type is capable of overloading each operator. If both the numerator and the denominator are integers, the integer type will perform the division operation and it will return an integer type. If you want floating point division, you must cast one or more of the number to floating point types before dividing them. For instance:

每种数据类型都能够重载每个运算符。如果分子和分母都是整数,则整数类型将执行除法运算并返回整数类型。如果要进行浮点除法,则必须在除法之前将一个或多个数字转换为浮点类型。例如:

int x = 13;
int y = 4;
float x = (float)y / (float)z;

or, if you are using literals:

或者,如果您使用的是文字:

float x = 13f / 4f;

Keep in mind, floating points are not precise. If you care about precision, use something like the decimal type, instead.

请记住,浮点数并不精确。如果您关心精度,请改用十进制类型之类的东西。

回答by L. Monty

Its just a basic operation.

Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3.

它只是一个基本的操作

记住当你学会分裂时。一开始我们解决了9/6 = 1 with remainder 3.

9 / 6 == 1  //true
9 % 6 == 3 // true

The /-operator in combination with the %-operator are used to retrieve those values.

/-operator 与 %-operator 结合用于检索这些值。

回答by eozten

Might be useful:

可能有用:

double a = 5.0/2.0;   
Console.WriteLine (a);      // 2.5

double b = 5/2;   
Console.WriteLine (b);      // 2

int c = 5/2;   
Console.WriteLine (c);      // 2

double d = 5f/2f;   
Console.WriteLine (d);      // 2.5

回答by z m

The result will always be of type that has the greater range of the numerator and the denominator. The exceptions are byte and short, which produce int (Int32).

结果将始终是分子和分母范围更大的类型。例外是 byte 和 short,它们产生 int (Int32)。

var a = (byte)5 / (byte)2;  // 2 (Int32)
var b = (short)5 / (byte)2; // 2 (Int32)
var c = 5 / 2;              // 2 (Int32)
var d = 5 / 2U;             // 2 (UInt32)
var e = 5L / 2U;            // 2 (Int64)
var f = 5L / 2UL;           // 2 (UInt64)
var g = 5F / 2UL;           // 2.5 (Single/float)
var h = 5F / 2D;            // 2.5 (Double)
var i = 5.0 / 2F;           // 2.5 (Double)
var j = 5M / 2;             // 2.5 (Decimal)
var k = 5M / 2F;            // Not allowed

There is no implicit conversion between floating-point types and the decimal type, so division between them is not allowed. You have to explicitly cast and decide which one you want (Decimal has more precision and a smaller range compared to floating-point types).

浮点类型和十进制类型之间没有隐式转换,因此不允许它们之间的划分。您必须显式转换并决定您想要哪个(与浮点类型相比,Decimal 具有更高的精度和更小的范围)。