【问题标题】:Android app Toast confusionAndroid 应用 Toast 混乱
【发布时间】:2018-12-14 14:52:12
【问题描述】:

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

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: Amount i got right 4 总共是 6"

为什么toast百分比是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());
    }

吐司说“你回答正确的问题是 0%”

【问题讨论】:

    标签: java android android-toast


    【解决方案1】:

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

    double percent = (right*100)/total ;
    

    或,

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

    希望这会奏效。


    更新:

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

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

    【讨论】:

    • 是的,第一个有效,为什么我的百分比公式无效?
    • 因为你使用了整数。当您将整数 2 除以整数 5 时 - 您得到整数 0,而不是浮点 0.2,然后将其乘以 100。0*100=0。只有在最后,它转换为双倍。为避免这种情况,请勿混淆不同类型的数量,或确保在除法之前将它们转换为正确的浮点类型。
    • @EugeneKartoyev ...也正确解释了。
    【解决方案2】:

    我想你可以稍微修改一下你的公式:

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

    除非您需要更精确的数字,否则无需使用 double。

    【讨论】:

      【解决方案3】:

      我不确定可以这样尝试:

      `Toast.makeText(this, "You answered " + pecent + "% of questions correct", Toast.LENGTH_SHORT).show();`
      

      【讨论】:

      • 我只是拿出百分比来以不同的方式进行测试,它不适用于百分比或我的方式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      相关资源
      最近更新 更多