首页 > 解决方案 > Android 应用 Toast 混乱

问题描述

我的应用程序是一个测验应用程序,其中有一部分会吐出用户在回答所有问题后正确回答的问题的百分比。

吐司出现了,但百分比始终为 0。

我前面有一些日志消息:

        Log.i("MainActivity", "Amount i got right "+Integer.toString(right));
        Log.i("MainActivity", "total is "+Integer.toString(total));

        Toast.makeText(this, "You answered " + (right/total)*100 + "% of questions correct", Toast.LENGTH_SHORT).show();

在日志中显示“I/MainActivity:我正确的数量 4 总计为 6”

为什么吐司百分比为0?

这是功能:

    int i = 0;
    int total = mQuestionBank.length;
    check = true;
    right = 0;
    while (i<total && check){
        if(mQuestionBank[i].isAlreadyAnswered()){
            if(mQuestionBank[i].isAnswerTrue()){
                right+=1;
                check = true;
            }

        }else{
            check = false;
        }
        i++;
    }

    if(check) {
        double percent = (right / total) * 100;
        Log.i("MainActivity", "Amount i got right "+Integer.toString(right));
        Log.i("MainActivity", "total is "+Integer.toString(total));

        Toast.makeText(this, "You answered " + (right/total)*100 + "% of questions correct", Toast.LENGTH_SHORT).show();
    }else {
        int question = mQuestionBank[mCurrentIndex].getTextResId();
        mQuestionTextView.setText(question);
        mTrueButton.setEnabled(!mQuestionBank[mCurrentIndex].isAlreadyAnswered());
        mFalseButton.setEnabled(!mQuestionBank[mCurrentIndex].isAlreadyAnswered());
    }

Toast 说“你答对了 0% 的问题”

标签: javaandroidandroid-toast

解决方案


代码没问题。你只需要一个简单的修改。试试这个 :

double percent = (right*100)/total ;

或者 ,

double percent = ((double)right/total)*100 ;

希望这会奏效。


更新 :

为什么您的代码不起作用?

right = 5和为例total = 10。由于变量 right 和 true 是整数,所以right/total总是为零,因为它们将返回一个整数值,并且.在整数值中不考虑后面的值。要解决此问题,您可以将 right 和 total 作为 double 变量或将 right 转换为 double 。和第一个解释公式。***因为right*100 = 500(right*100)/total = 500/10 = 50


推荐阅读