c# 否则无法按预期工作

本文关键字:工作 | 更新日期: 2023-09-27 18:35:18

    {
        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!为什么会这样?提前谢谢你。

c# 否则无法按预期工作

你必须让它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的条件分支中。

因为这个

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会怎样?