Ints and Doubles doing division

后端 未结 5 1858
挽巷
挽巷 2021-01-19 21:33

Short version: Why don\'t I have to coerce 60, and int, into a double, so that I can use division with another double if I DO care about the fractional part?

Long ve

相关标签:
5条回答
  • 2021-01-19 21:41

    You are right. The int 60 is promoted to double automatically. Writing 60.0 is correct, but redundant.

    C# language specification, "7.2.6.2 Binary numeric promotions": http://msdn.microsoft.com/en-us/library/aa691330.aspx

    0 讨论(0)
  • 2021-01-19 21:47

    Converting your durationInSeconds is enough. It will produce a double, and will round up to 2.

    0 讨论(0)
  • 2021-01-19 21:50

    Dividing double by an integer will result in double.

    No need for 60.0. You can use 60.0 and drop the double cast, instead. No need to use both. It is completely redundant.

    0 讨论(0)
  • 2021-01-19 21:57

    Here are the relevant division operators:

    public static double operator /(double x, double y)
    public static int operator /(int x, int y)
    

    There is an implicit conversion from int to double, but not the other way round... so if you divide an int by an int, you'll use the integer form... but if either operand is a double, it will use the double form.

    There's no need to make both operands double - but your code would be at least shorter if you made the divisor operand a double instead of casting:

    int durationInMinutes = (int) Math.Ceiling(durationInSeconds / 60.0);
    

    Personally I find that easier to read... but it's a personal choice.

    If you want to prove to your boss that it's really doing floating point division, use iladsm or reflector (in IL mode) on your code - it will show an ldc.r8 instruction for the constant, which means a double value.

    0 讨论(0)
  • 2021-01-19 22:01

    You can't divide a double by an integer, so the compiler will cast the integer to a double.

    So, the expressions (double)durationinseconds / 60 and (double)durationinseconds / 60.0 will result in identical code being created.

    I prefer using 60.0 in this case just to make it more visible what the code is actually doing.

    0 讨论(0)
提交回复
热议问题