I have a code where the variable "sum" is an integer. 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. I tried the above code with the data type "double" and I am getting the same answer. 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.
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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.