请检查以下Android代码
private void preMealChartCreator(int numberOfPreMealLow, int numberOfPreMealNormal, int numberOfPreMealHigh, int totalReadings) {
Log.d("OverViewFragment","chart_low: "+numberOfPreMealLow+" chart_normalssss: "+numberOfPreMealNormal+" chart_high: "+numberOfPreMealHigh+" chart_total: "+totalReadings);
int preMealLowPercentage = (int)((numberOfPreMealLow/totalReadings)*100);
double preMealNormalPercentage = (double)((numberOfPreMealNormal/totalReadings)*100);
int preMealHighPercentage = (int)((numberOfPreMealHigh/totalReadings)*100);
Log.d("OverViewFragment","chart_low: "+"low_percentage: "+preMealLowPercentage+" normal_percentage: "+preMealNormalPercentage+ "high_percentage: "+preMealHighPercentage);
Log.d("OverViewFragment","chart_low: "+ " chart_normalssss: "+numberOfPreMealNormal+ " chart_total: " +totalReadings+" normal_manual: "+ (1/5)*100);
lowBarView.set(Color.GRAY, preMealLowPercentage);
normalBarView.set(Color.GREEN, (int)preMealNormalPercentage);
highBarView.set(Color.YELLOW, preMealHighPercentage);
verHighBarView.set(Color.RED, 6);
lowTextView.setText(getPercentage(preMealLowPercentage));
normalTextView.setText(getPercentage((int)preMealNormalPercentage));
highTextView.setText(getPercentage(preMealHighPercentage));
veryHighTextView.setText(getPercentage(6));
}
无论我做什么,我的百分比总是为0.我想检查是否有null
或0,所以我打印了日志,一切都很好。记录在
01-13 18:50:08.647 9232-9232/xx.com.au.xxD/OverViewFragment: chart_low: 0 chart_normalssss: 1 chart_high: 2 chart_total: 5
01-13 18:50:08.647 9232-9232/xx.com.au.xxD/OverViewFragment: chart_low: low_percentage: 0 normal_percentage: 0.0high_percentage: 0
01-13 18:50:08.647 9232-9232/xx.com.au.xxD/OverViewFragment: chart_low: chart_normalssss: 1 chart_total: 5 normal_manual: 0
我甚至尝试手动转换为double
,然后硬编码值,nothi8ng工作。这有什么不对?
答案 0 :(得分:2)
在分割之前将一个变量投射到float
:
int preMealLowPercentage = (int)((numberOfPreMealLow/(float)totalReadings)*100);
因为否则你会用整数操作。
或者您可以简单地移动*100
:
int preMealLowPercentage = (int)((numberOfPreMealLow*100/totalReadings));