【问题标题】:Android divisions always results in 0Android部门总是导致0
【发布时间】:2017-01-13 13:23:20
【问题描述】:

请检查以下安卓代码

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,然后硬编码值,但没有任何效果。这里有什么问题?

【问题讨论】:

    标签: java android math double integer-division


    【解决方案1】:

    在除法之前将变量之一转换为float

    int preMealLowPercentage = (int)((numberOfPreMealLow/(float)totalReadings)*100);

    因为否则您将使用整数进行操作。

    或者您可以简单地移动*100,例如:

    int preMealLowPercentage = (int)((numberOfPreMealLow*100/totalReadings));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多