我总共有 40 个问题,Correct_Answer = 36 和 Incorrect_Answer = 4。
我如何将它乘以 android 程序中的百分比。
心智的结果总是以0.0%显示
代码:
int total_score = (Correct_Answer/40)*0.01);
Txt_Total_Score.setText(Integer.toString(total_score + "%"));
我总共有 40 个问题,Correct_Answer = 36 和 Incorrect_Answer = 4。
我如何将它乘以 android 程序中的百分比。
心智的结果总是以0.0%显示
代码:
int total_score = (Correct_Answer/40)*0.01);
Txt_Total_Score.setText(Integer.toString(total_score + "%"));
您正在两个整数之间执行整数除法,其中除数大于被除数,并且由于 36/40 会给您 0.9,并且总分是 int,因此小数部分被去除。因此,您必须将除数和除数中的一个提升为浮动执行演员:
int 最后一行,因为你将一个字符串与一个整数连接起来,你会得到一个字符串作为结果(Integer.toString 没用)
float correctAnswerFloat = (float)Correct_Answer / 40 ;
int total_score = (int )( correctAnswerFloat * 100 );
Txt_Total_Score.setText(total_score + " %"));
而不是整数使用浮点数。并乘以 100。
float total_score = ((float)Correct_Answer/40)*100);
Txt_Total_Score.setText(Float.toString(total_score + "%"));
你应该试试这个:
int total_score = (Correct_Answer*100)/40;
在你所做的事情中,括号给出了 0int
位小数的结果。所以先乘以 100,然后除以总问题。
试试这样:
float total_score = ((float)Correct_Answer * 100 / 40); // Edited with information from comments :)
Txt_Total_Score.setText(Float.toString(total_score) + "%");