C# simple divide problem

前端 未结 9 1010
感动是毒
感动是毒 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 01:50

    60 and 23 are integer literals so you are doing integer division and then assigning to a double. The result of the integer division is 2.

    Try

    double result = 60.0 / 23.0;
    

    Or equivalently

    double result = 60d / 23d;
    

    Where the d suffix informs the complier that you meant to write a double literal.

    0 讨论(0)
  • 2020-12-11 01:53

    Haven't used C# for a while, but you are dividing two integers, which as far as I remember makes the result an integer as well.

    You can force your number literals to be doubles by adding the letter "d", likes this:

    double result = 60d / 23d;
    
    0 讨论(0)
  • 2020-12-11 01:59

    double result = 60.0 / 23.0;

    0 讨论(0)
  • 2020-12-11 01:59

    It is best practice to correctly decorate numerals for their appropriate type. This avoids not only the bug you are experiencing, but makes the code more readable and maintainable.

    double x = 100d;
    single x = 100f;
    decimal x = 100m;
    
    0 讨论(0)
  • 2020-12-11 01:59

    convert the dividend and divisor into double values, so that result is double
    double res= 60d/23d;

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

    (double) 60 / 23

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