Dividing two integers to a double in java

吃可爱长大的小学妹 提交于 2019-11-27 15:28:41

This line here d = w[L] /v[L]; takes place over several steps

d = (int)w[L]  / (int)v[L]
d=(int)(w[L]/v[L])            //the integer result is calculated
d=(double)(int)(w[L]/v[L])    //the integer result is cast to double

In other words the precision is already gone before you cast to double, you need to cast to double first, so

d = ((double)w[L])  / (int)v[L];

This forces java to use double maths the whole way through rather than use integer maths and then cast to double at the end

Actaully w[L]/v[L] here both are integer, on division operation it loose precision and trucated to integer value, latter trucated integer is converted to double.

Solution would be convert operand or divisor or both to double, division operaion would produce decimal value.

d = w[L]/(double)v[L];

use like following

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