简体   繁体   English

JAVA:没有得到我想要的小数位数

[英]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.

相关问题 将Java十六进制转换为十进制时出现错误 - I am getting an error when converting Java hexadecimal to decimal 如何在数字后得到一定数量的小数点? 爪哇 - How to get a certain number of decimal points after the number? java 为什么使用JAVA将Excel工作表中的行数设为0? - Why am I getting the number of rows in an Excel sheet as 0 using JAVA? 我想使用Java在文件的最后一行中添加一些字符串,但是我被卡住了,需要帮助:) - I want to add some string in Last Line of File using Java, but i am getting stuck , Need help :) 我想用java程序发送电子邮件。 我得到如下的豁免权 - I want to send email using java program. I am getting the excetion as below 我想在数组中找到唯一的重复值,但我没有得到下面是我在 Java 中的代码 - I want to find unique duplicates value in array,but i am not getting below is my code in java 所以我正在尝试使用 2 个线程打印奇数和偶数,但我没有得到我想要的 output,我希望它按 1 到 10 的顺序打印 - so i am trying to print odd and even number using 2 threads but i am not getting the output i want, i want it to print in 1 to 10 in order 我该如何解决这个问题我想将十进制数转换为二进制数 - how can i fix this i want to convert decimal number to binary 如何在java中将字符串转换为数字? 但我不是在寻找 hashCode,因为它不会给出唯一编号。 至少我想要同样的数学逻辑 - How to convert string to number in java ? But i am not looking for hashCode as it wont give unique number. at least i want math logic for same 我想检查一个数字是否是二进制数或不是十进制数,但它没有用 - I want to check if a number is binary or not in decimal numbers but it didnt work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM