C# simple divide problem

前端 未结 9 1013
感动是毒
感动是毒 2020-12-11 01:40

I have this:

 double result = 60 / 23;

In my program, the result is 2, but correct is 2,608695652173913. Where is problem?

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 02:08

    You can use any of the following all will give 2.60869565217391:

     double result = 60 / 23d;  
     double result = 60d / 23;  
     double result = 60d/ 23d;  
     double result = 60.0 / 23.0;   
    

    But

    double result = 60 / 23;  //give 2
    

    Explanation:

    if any of the number is double it will give a double


    EDIT:

    Documentation

    The evaluation of the expression is performed according to the following rules:

    • If one of the floating-point types is double, the expression evaluates to double (or bool in the case of relational or Boolean expressions).

    • If there is no double type in the expression, it evaluates to float (or bool in the case of relational or Boolean expressions).

提交回复
热议问题