java - 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% 的问题”
解决方案
代码没问题。你只需要一个简单的修改。试试这个 :
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
。
推荐阅读
- python - 两个数据帧之间的比较?
- gremlin - tinkerpop gremlin clear 控制台不工作
- spring-cloud - feign.FeignException:在微服务调用中读取状态 404
- python - 无法使用 xmlrunner 为 unittest 打印日志记录输出
- reactjs - 使用反应导航移动到新页面后每次调用函数/解析器?
- c++ - 为什么这段代码只适用于 && 而不是 ||?使用 || 代替 && 程序永远持续下去
- javascript - Quill 示例 => 未捕获的错误:[Parchment] 无法将链接插入块中
- oracle - Docker 容器内的 Oracle 表单和报表服务器
- c# - 在 for 循环中从 ICollection 列表读取的 Asp.NET CSHTML 数据在页面加载时未设置
- node.js - 错误无法使用 express 和节点发布 /