I'm attempting to make a random number generator that then selects one of three options based on the random number. I would like to use > x < as the second choice of three but it gives me an error:
Operator '>' cannot be applied to operands of type 'bool' and 'int'
Here's the code:
int rand;
Random myRandom = new Random();
rand = myRandom.Next(0, 90);
if (rand < 33)
{
}
if (33 > rand < 66)
{
}
if (rand > 66)
{
}
Well the simplest option is to use else if
so you only need to check one condition anyway - which means it would handle 33 as well (currently not handled):
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]");
}
If you do need to test two conditions, however, you just want &&
to check that they're both true:
// 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 you find yourself doing this a lot, you might want to have an extension method so you can say:
if (rand.IsInRange(33, 66))
where IsInRange
would just be:
public static bool IsInRange(this int value, int minInclusive, int maxExclusive)
{
return value >= minInclusive && value < maxExclusive;
}
See more on this question at Stackoverflow