Java Division error

旧时模样 提交于 2019-11-27 07:57:25

问题


I have the following variables:

int first = 0;
int end = 0;

Declare in the public class.

Within a method:

double diff = end / first;
double finaldiff = 1 - diff;

The end variable on System.out.println is 527, the first is 480.

Why is the answer for diff coming out as 1? It should be 1.097916667, I thought using a double would enable me to calculate into decimals?


回答1:


Dividing two ints will get you an int, which is then implicitly converted to double. Cast one to a double before the divison:

double diff = (double)end / first;


来源:https://stackoverflow.com/questions/10376322/java-division-error

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