How to get fractions in an integer division? [duplicate]

天涯浪子 提交于 2019-11-26 16:38:44

You need to cast one or the other to a float or double.

int x = 1;
int y = 3;

// Before
x / y; // (0!)

// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)

Of course, make sure that you are store the result of the division in a double or float! It doesn't do you any good if you store the result in another int.


Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]"):

Don't pass a double or float to setIntValue when you have setDoubleValue, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.

For example, on my system, the file:

#include <stdio.h>
int main()
{
    double x = 3.14;
    printf("%d", x);
    return 0;
}

outputs:

1374389535

because the double was attempted to be read as an int.

Use type-casting. For example,

main()
    {
        float a;
        int b = 2, c = 3;
        a = (float) b / (float) c;     // This is type-casting
        printf("%f", a);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!