我写了一个用户玩游戏并猜测答案的程序。 除了我的数组之外,一切都运行良好,程序有两个数组,第一个是usersAnswers,其中包含用户选择,第二个名为decompTimeArray,其中包含正确的答案。我写了一个方法,程序将比较两个数组并计算用户有多少对错,并将它们的值放在两个单独的标签中。该程序运行正常但它总是给我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();
}
}
}
答案 0 :(得分:0)
如果wrong
是integer
,则您在此处进行整数除法:percentage = (wrong / 5) * 100;
例如,如果错误为4
,您将获得4/5 = 0 * 100 = 0
。因此,您始终会显示0
。
您需要将错误转换为double
(或decimal
或float
)或值5本身(这是首选,因为您无法真正得到'偏'答案)重写5.0
。
所以
percentage = (int)((wrong / 5.0) * 100);
^
|
This will be a double-|
将触发正确的分割类型;现在,该操作将计算为4 / 5.0 = 0.8*100 = 80