[英]JAVA: Am not getting the number of decimal points I want
I have a code where the variable "sum" is an integer. 我有一个代码,其中变量“ sum”是整数。 I am trying to find the average, such that
我试图找到平均值,这样
int sum = 1;
float avg = 0;
//later on in the code
avg = (float)sum/37;
According to Android Studio debugger, the value stored in avg is 0.0, and not the desired 0.02... I want more decimal points, but my answer is getting rounded up to 1 decimal place. 根据Android Studio调试器,avg中存储的值为0.0,而不是所需的0.02 ...我想要更多的小数点,但是我的答案被四舍五入到小数点后1位。 I tried the above code with the data type "double" and I am getting the same answer.
我用数据类型“ double”尝试了上面的代码,并且得到了相同的答案。 Anyone have any tips?
有人有提示吗?
Try with: 尝试:
avg = sum/37f;
Your problem is integer/integer = integer In your case the cast happens when the integer computation is done, which is to late. 您的问题是integer / integer = integer在您的情况下,强制转换发生在整数计算完成时,这很晚。
Your problem is that operator precedence of your code resolved to: 您的问题是代码的运算符优先级解析为:
avg = (float)(sum/37);
This means that you're still doing int / int
math, which results in 0
, before the cast to float
. 这意味着您仍在进行
int / int
数学运算,结果强制为float
之前为0
。
There are two ways to fix it: 有两种解决方法:
avg = ((float)sum)/37; // cast sum to float before division
avg = sum/37f; // change to a float literal so sum is coerced to float for you
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.