{
Random r = new Random();
int current = 0;
int noa = 0;
while (current != 6) {
current =r.Next(1,7);
noa += 1;
Console.WriteLine(current + " has been rolled.");
}
if (noa >= 10)
{
Console.WriteLine("You were unlucky and it took you "+ noa + " times to roll a 6!");
}
if (noa <= 5)
{
Console.WriteLine("You were quite lucky and it took you " + noa + " times to roll a 6!");
}
else
{
Console.WriteLine("It took you " + noa + " times to roll a 6!");
}
Console.ReadKey();
}
}
} 因此,当noa(尝试次数)高于10时会出现问题,它显示的是:
2已经滚动。
5已经滚动。
4已经滚动。
5已经滚动。
5已经滚动。
1已经滚动。
2已经滚动。
1已经滚动。
3已经滚动。
4已经滚动。
6已经滚动。
你运气不好,你花了11次才打出一个6! 你花了11次滚动了6次!
我不想发生的事情是控制台写第二行“你花了11次才打了6个!”。 为什么会这样?提前谢谢。
答案 0 :(得分:7)
你必须把它elseif
if (noa >= 10)
{
Console.WriteLine("You were unlucky and it took you "+ noa + " times to roll a 6!");
}
else if (noa <= 5)
{
Console.WriteLine("You were quite lucky and it took you " + noa + " times to roll a 6!");
}
else
{
Console.WriteLine("It took you " + noa + " times to roll a 6!");
}
修改强>
同意@Kalmino,问题的原因是所有条件都在if... elseif... else
的一个条件分支中一起处理。
答案 1 :(得分:3)
因为这个
if (noa <= 5)
{
Console.WriteLine("You were quite lucky and it took you " + noa + " times to roll a 6!");
}
else
{
Console.WriteLine("It took you " + noa + " times to roll a 6!");
}
noa>5
会怎样?