[英]Android app Toast confusion
My app is a quiz app, in it there's a part that spits out a percent of questions the user got correct after answering all the questions as a Toast. 我的应用程序是一个测验应用程序,其中有一部分在用Toast回答所有问题之后吐出了用户纠正的百分比问题。
The toast is showing up but the percentage is always coming up as 0. 吐司正在出现,但百分比总是为0。
I have some log messages just infront: 我面前有一些日志消息:
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();
In the log it says "I/MainActivity: Amount i got right 4 total is 6" 在日志中它显示“I / MainActivity:我正确的数量4总计是6”
Why is the toast percentage coming as 0?? 为什么吐司百分比为0?
here's the function: 这是功能:
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());
}
The Toast says "You answered 0% of the questions correct" 吐司说“你回答了0%的问题是正确的”
The code is OK . 代码没问题。 You just need a simple modification .
你只需要一个简单的修改。 Try this :
试试这个 :
double percent = (right*100)/total ;
or , 要么 ,
double percent = ((double)right/total)*100 ;
Hope this will work . 希望这会奏效。
Update : 更新:
As a example take right = 5
and total = 10
. 例如,取
right = 5
, total = 10
。 As the variable right and true are integers so right/total
will be 0 zero always because they will return a integer value and the value after .
因为变量right和true是整数所以
right/total
将为0,因为它们将返回一个整数值和后面的值.
is not considered in integer value . 不被视为整数值。 To solve the problem you can take right and total as double variable or cast the right as double .
要解决这个问题,您可以将right和total视为双变量,或者将右侧变为double。 And the first explained formula .
并首先解释了公式。 ***Because
right*100 = 500
and (right*100)/total = 500/10 = 50
. ***因为
right*100 = 500
和(right*100)/total = 500/10 = 50
。
I guess you could just modify your formula slightly: 我想你可以稍微修改一下你的公式:
Toast.makeText(this, "You answered " + ((right*100)/total) + "% of questions correct", Toast.LENGTH_SHORT).show();
No need to use double unless you need more exact numbers. 除非您需要更准确的数字,否则无需使用double。
我不确定这样做:
`Toast.makeText(this, "You answered " + pecent + "% of questions correct", Toast.LENGTH_SHORT).show();`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.