比较两个数组,同时计算正确答案和错误答案的数量
本文关键字:答案 错误 计算 两个 数组 比较 | 更新日期: 2023-09-27 18:00:56
我写了一个程序,用户在其中玩游戏并猜测答案。除了我的数组之外,一切都很好,程序有两个数组,第一个是usersAnswers,它包含用户的选择,第二个是decodeTimeArray,它包含正确的答案。我写了一个方法,程序将比较两个数组,计算用户得到的正确和错误答案的数量,并将其值放在两个单独的标签中。该程序运行良好,但正确和不正确的标签总是给我0,如果你能帮助我解决这个小问题,并使程序正确计算答案,我将不胜感激。这是我的代码:
public void usersAnswers()
{
userAnswers[0] = newspaperLbl.Text;
userAnswers[1] = aluminumCanLbl.Text;
userAnswers[2] = glassBottleLbl.Text;
userAnswers[3] = plasticbagLbl.Text;
userAnswers[4] = cupLbl.Text;
}
public void correctAnswers()
{
decompTimeArray[0] = "6 Weeks";
decompTimeArray[1] = "10-20 Years";
decompTimeArray[2] = "80-200 Years";
decompTimeArray[3] = "1,000,000 Years";
decompTimeArray[4] = "Never";
}
public void compareArrays()
{
bool arraysEqual = true;
int index;
if (userAnswers.Length != decompTimeArray.Length)
{
arraysEqual = false;
}
for (index = 0; index < userAnswers.Length; index++)
{
if (decompTimeArray[index] != userAnswers[index])
{
arraysEqual = false;
wrong++;
}
else
{
arraysEqual = false;
right++;
}
/*This part of the program will compare the arrays from
* methods 1,2 we use a for loop*/
}
if (arraysEqual)
{
Results Result = new Results();
Result.correctAnswersLbl.Text = right.ToString("n");
}
else
{
Results Result = new Results();
Result.incorrectAnswersLbl.Text = wrong.ToString("n");
}
}
public void checkAnswersBtn_Click(object sender, EventArgs e)
{
Results Result = new Results();
Result.userAnswer1Label.Text = newspaperLbl.Text;
Result.userAnswer2Label.Text = aluminumCanLbl.Text;
Result.userAnswer3Label.Text = glassBottleLbl.Text;
Result.userAnswer4Label.Text = plasticbagLbl.Text;
Result.userAnswer5Label.Text = cupLbl.Text;
Result.correctAnswersLbl.Text = right.ToString("n");
Result.incorrectAnswersLbl.Text = wrong.ToString("n");
percentage = (wrong / 5) * 100;
Result.percentageLbl.Text = percentage.ToString("p");
this.Hide();
Introduction Intro = new Introduction();
Intro.Hide();
Result.ShowDialog();
}
}
}
如果wrong
是integer
,则在此处执行整数除法:percentage = (wrong / 5) * 100;
因此,如果4
是错误的,例如,您将得到4/5 = 0 * 100 = 0
。因此,您将始终显示0
。
您需要通过重写5.0
将error转换为double
(或decimal
或float
(,或转换为值5本身(这更可取,因为您无法真正获得"部分"答案(。
所以
percentage = (int)((wrong / 5.0) * 100);
^
|
This will be a double-|
将触发正确的划分类型;操作现在将被计算为4 / 5.0 = 0.8*100 = 80