c#否则没有按预期工作

tag*_*ito -3 c# if-statement while-loop

    {
        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();


    }
}
Run Code Online (Sandbox Code Playgroud)

当noa(尝试次数)高于10时会出现问题,它显示的是:

2已经滚动.
5已经滚动.
4已滚动.
5已经滚动.
5已经滚动.
1已经滚动.
2已经滚动.
1已经滚动.
3已经滚动.
4已滚动.
6已经滚动.
你运气不好,你花了11次才打了6个!
你花了11次滚动了6次!

我不希望发生的是控制台写第二行"它花了你11次滚动6!".为什么会这样?先感谢您.

Car*_*ine 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!");
}
Run Code Online (Sandbox Code Playgroud)

编辑 同意@Kalmino,问题的原因是所有条件在一个条件分支中一起处理if... elseif... else.

  • @tagito你拥有它的方式(与此相反)是将> = 10和下一个if/else视为两个单独的语句.如果CarbineCoder放入其中的其他3个加入它们,那么它一起评估它们而不是检查> = 10然后检查<= 5或Else. (2认同)