java - Android 除法始终结果为 0

标签 java android math double integer-division

请检查以下 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,然后硬编码值,但没有效果。这里出了什么问题?

最佳答案

在除法之前将其中一个变量转换为float:

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

因为否则你正在使用整数进行操作。

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

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

关于java - Android 除法始终结果为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635633/

相关文章:

android - 选项 android.useNewApkCreator 已弃用

c# - 在 C# 中舍入为偶数

java - 通过HQL连接两、三个相关表

java:159: 错误: 找不到适合 put(String,int) 的方法

Java Swing BorderLayout resize困难

java - 从父类(super class)方法调用子类方法?

android - 单个 ListView 内的多个 ViewPagers 崩溃

java - 找不到 R.layout - 应用名称。只有安卓布局

c# - 如何使用 NET Math.Round(<decimal>,<int>,MidpointRounding.AwayFromZero) 正确舍入

php - while循环进入2个不同的div?