Dividing two integers in Java gives me 0 or 100?

后端 未结 5 882
悲&欢浪女
悲&欢浪女 2020-12-01 20:52

I\'m trying to divide two integers and multiply by 100 but it keeps giving only 0 or 100. Can someone help me?

    int x= (a/b)*100;

if a w

相关标签:
5条回答
  • 2020-12-01 21:24

    What you could do is force it to divide a and b as doubles thus:

    int x = (int) (((double) a / (double) b) * 100);
    
    0 讨论(0)
  • 2020-12-01 21:25

    Integer division has no fractions, so 500 / 1000 = 0.5 (that is no integer!) which gets truncated to integer 0. You probably want

    int x = a * 100 / b;
    
    0 讨论(0)
  • 2020-12-01 21:30

    This sounds like you are not correctly typing your variables; two integer divisions result in an integer, not a float or double. For example:

    (int)3 / (int)5 = 0
    (float)3 / (float)5 = 0.6
    
    0 讨论(0)
  • 2020-12-01 21:42

    Try this:

    int x = a * 100 / b;
    

    The idea is, you are first doing a / b, and because it's an integer operation, it'll round the result to 0. Doing a * 100 first should fix it.

    0 讨论(0)
  • 2020-12-01 21:51

    Simplest, most effective way I found:

    double x = (double) a / (double) b
    
    0 讨论(0)
提交回复
热议问题