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

前端 未结 8 912
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:32

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++?)

In C#:

fl         


        
8条回答
  •  攒了一身酷
    2020-11-21 05:21

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

    • 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.

提交回复
热议问题