如何做> x<在C#中

时间:2014-10-05 15:56:11

标签: c# random

我正在尝试创建一个随机数生成器,然后根据随机数选择三个选项之一。我想用> x<作为三个中的第二个选择,但它给了我一个错误:

运营商'>'不能应用于'bool'和'int'

类型的操作数

以下是代码:

        int rand;
        Random myRandom = new Random();
        rand = myRandom.Next(0, 90);

        if (rand < 33)
        {

        }

        if (33 > rand < 66)
        {

        }

        if (rand > 66)
        {

        }

3 个答案:

答案 0 :(得分:3)

最简单的选择是使用else if所以你只需要检查一个条件 - 这意味着它也会处理33(目前没有处理):

if (rand < 33)
{
    Console.WriteLine("rand was in the range [0, 32]");
}
else if (rand < 66)
{
    Console.WriteLine("rand was in the range [33, 65]");
}
else
{
    Console.WriteLine("rand was in the range [66, 89]");
}

如果你需要测试两个条件,你只需要&&检查它们是否都是真的:

// I've deliberately made this >= rather than 33. If you really don't want to do
// anything for 33, it would be worth making that clear.
if (rand >= 33 && rand < 66)

如果你发现自己做了很多,你可能想要一个扩展方法,所以你可以说:

if (rand.IsInRange(33, 66))

IsInRange只是:

public static bool IsInRange(this int value, int minInclusive, int maxExclusive)
{
    return value >= minInclusive && value < maxExclusive;
}

答案 1 :(得分:2)

您应该使用&&&运算符,如

if (rand > 33 && rand < 66)
{

}

这可确保兰特为less than AND greater,然后指定值

答案 2 :(得分:0)

要检查值的两个边界,您需要进行两次比较。

您可能希望在该比较中使用<=运算符而不是<,否则代码将对值3366不执行任何操作:

    if (rand < 33)
    {

    }

    if (33 <= rand && rand < 66)
    {

    }

    if (rand >= 66)
    {

    }

你也可以使用else来摆脱一些比较:

    if (rand < 33)
    {

    }
    else if (rand < 66)
    {

    }
    else
    {

    }

注意:您在089之间有一个随机值,因此如果您希望在三分之一的案例中使用每个if语句,则应使用值{{ 1}}和30代替6033