Possible Loss of Fraction

后端 未结 5 1592
慢半拍i
慢半拍i 2020-12-02 14:12

Forgive me if this is a naïve question, however I am at a loss today.

I have a simple division calculation such as follows:

double returnValue = (myO         


        
5条回答
  •  一整个雨季
    2020-12-02 14:23

    Assuming that myObject.Value is an int, the equation myObject.Value / 10 will be an integer division which will then be cast to a double.

    That means that myObject.Value being 12 will result in returnValue becoming 1, not 1.2.

    You need to cast the value(s) first:

    double returnValue = (double)(myObject.Value) / 10.0;
    

    This would result in the correct value 1.2, at least as correct as doubles will allow given their limitations but that's discussed elsewhere on SO, almost endlessly :-).

提交回复
热议问题