Java Arithmetic division

匆匆过客 提交于 2019-12-08 08:08:18

问题


public class test {
  public static void main(String[] args) {
   int total = 2;
   int rn = 1;
   double rnp = (rn / total) * 100;
   System.out.println(rnp);
 }
}

Why it prints 0.0 instead of 50.0?

https://www.google.com/search?q=100*(1%2F2)&aq=f&oq=100*(1%2F2)


回答1:


The division occurs in integer space with no notion of fractions, you need something like

double rnp = (rn / (double) total) * 100



回答2:


You are invoking integer division here

(rn / total)

Integer division rounds towards zero.

Try this instead:

double rnp = ((double)rn / total) * 100;



回答3:


In java, and most other programming languages, when you divide two integers, the result is also an integer. The remainder is discarded. Thus, 1 / 2 returns 0. If you want a float or double value returned, you need to do something like 1 * 1.0 / 2, which will return 0.5. Multiplying or dividing an integer by a double or float converts it to that format.




回答4:


public class test
{
  public static void main(String[] args) 
  {
   int total = 2;
   int rn = 1;
   double rnp = (rn / (float)total) * 100;
   System.out.println(rnp);
 }
}


来源:https://stackoverflow.com/questions/15649057/java-arithmetic-division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!