我正在尝试做一些简单的百分比,而我的结果总是为零。
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
Log.d("taste", rate);
int rateNum = Integer.parseInt(rate);
Log.d("taste", "rateNum is " + rateNum);
int percent = rateNum / count;
percent = percent * 100;
Log.d("taste", "percent is " + percent);
奇怪的部分是看我的Log我的rateNum和count变量都是数字而不是零:
06-26 21:52:44.319: D/taste(11812): count it:20
06-26 21:52:44.319: D/taste(11812): 13
06-26 21:52:44.319: D/taste(11812): rateNum is 13
06-26 21:52:44.319: D/taste(11812): percent is 0
06-26 21:52:44.319: D/taste(11812): 3
06-26 21:52:44.319: D/taste(11812): rateNum is 3
06-26 21:52:44.319: D/taste(11812): percent is 0
06-26 21:52:44.319: D/taste(11812): 3
06-26 21:52:44.319: D/taste(11812): rateNum is 3
06-26 21:52:44.319: D/taste(11812): percent is 0
06-26 21:52:44.319: D/taste(11812): 1
06-26 21:52:44.319: D/taste(11812): rateNum is 1
06-26 21:52:44.319: D/taste(11812): percent is 0
所以我不知道为什么我的百分比一直为零。
答案 0 :(得分:2)
您遇到了数字类型的错误。
当你获得rateNum时,它是int
,因为是计数。由于int / int = int(截断小数),您将0乘以100得到0。
解决方案如下:
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
Log.d("taste", rate);
double rateNum = Double.parseInt(rate);
Log.d("taste", "rateNum is " + rateNum);
double percent = rateNum / count;
percent = percent * 100;
Log.d("taste", "percent is " + percent);
答案 1 :(得分:1)
您可能想尝试
int percent = (100*rateNum) / count;
或使用浮点数学。你的价值被四舍五入为零,然后永远不会恢复。
答案 2 :(得分:0)
您使用int类型来保存百分比,因此像{0.8}这样的数字将在int percent = rateNum / count;
处舍入为0
改为使用
float percent = rateNum / count;