C# simple divide problem

前端 未结 9 1012
感动是毒
感动是毒 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).

    0 讨论(0)
  • 2020-12-11 02:09

    It will work

    double result = (double)60 / (double) 23;
    

    Or equivalently

    double result = (double)60 /  23;
    
    0 讨论(0)
  • 2020-12-11 02:16

    To add to what has been said so far... 60/23 is an operation on two constants. The compiler recognizes the result as a constant and pre-computes the answer. Since the operation is on two integers, the compiler uses an integer result The integer operation of 60/23 has a result of 2; so the compiler effective creates the following code:

    double result = 2;
    

    As has been pointed out already, you need to tell the compiler not to use integers, changing one or both of the operands to non-integer will get the compiler to use a floating-point constant.

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