Why does Decimal.Divide(int, int) work, but not (int / int)?

后端 未结 8 849
旧时难觅i
旧时难觅i 2020-12-08 03:18

How come dividing two 32 bit int numbers as ( int / int ) returns to me 0, but if I use Decimal.Divide() I get the correct answer? I\'m by no means

相关标签:
8条回答
  • 2020-12-08 04:21

    I reckon Decimal.Divide(decimal, decimal) implicitly converts its 2 int arguments to decimals before returning a decimal value (precise) where as 4/5 is treated as integer division and returns 0

    0 讨论(0)
  • 2020-12-08 04:23

    The following line:

    int a = 1, b = 2;
    object result = a / b;
    

    ...will be performed using integer arithmetic. Decimal.Divide on the other hand takes two parameters of the type Decimal, so the division will be performed on decimal values rather than integer values. That is equivalent of this:

    int a = 1, b = 2;
    object result = (Decimal)a / (Decimal)b;
    

    To examine this, you can add the following code lines after each of the above examples:

    Console.WriteLine(result.ToString());
    Console.WriteLine(result.GetType().ToString());
    

    The output in the first case will be

    0
    System.Int32
    

    ..and in the second case:

    0,5
    System.Decimal
    
    0 讨论(0)
提交回复
热议问题