Why does int exp1 = 14/20*100; equals '0' in java?

后端 未结 4 1541
不知归路
不知归路 2020-12-12 07:07

I\'m trying to do some basic math and it keeps popping up as 0. I\'m sure it has to do with it being an int but I don\'t know how to work around it

相关标签:
4条回答
  • 2020-12-12 07:14

    That's integer division.

    To get non-integer results, use doubles instead.

    0 讨论(0)
  • 2020-12-12 07:37

    Your result is being cast as an int, so you are losing precision.

    Try

    double exp1 = 14/20.0*100;
    
    0 讨论(0)
  • 2020-12-12 07:38

    You can change it to 14*100/20 - and then it will give what you want.

    I.e. change the sequence of operations (14/20 is 0)

    0 讨论(0)
  • 2020-12-12 07:39

    This is not special to blackberry, it's standard java behaviour.

    This is because you're doing integer math:

    int subexpr1 = 14 / 20; // 0
    int subexpr2 =  subexpr1 * 100; // 0
    

    Use a double instead or change the order

    int expr1 = (int) 14.0/20 * 100; // Very small possibility of rounding errors
    int expr2 = 14 * 100 / 20; // Will ignore fraction parts
    
    0 讨论(0)
提交回复
热议问题