我正在尝试创建一个随机数生成器,然后根据随机数选择三个选项之一。我想用> x<作为三个中的第二个选择,但它给了我一个错误:
运营商'>'不能应用于'bool'和'int'
类型的操作数以下是代码:
int rand;
Random myRandom = new Random();
rand = myRandom.Next(0, 90);
if (rand < 33)
{
}
if (33 > rand < 66)
{
}
if (rand > 66)
{
}
答案 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)
要检查值的两个边界,您需要进行两次比较。
您可能希望在该比较中使用<=
运算符而不是<
,否则代码将对值33
和66
不执行任何操作:
if (rand < 33)
{
}
if (33 <= rand && rand < 66)
{
}
if (rand >= 66)
{
}
你也可以使用else
来摆脱一些比较:
if (rand < 33)
{
}
else if (rand < 66)
{
}
else
{
}
注意:您在0
和89
之间有一个随机值,因此如果您希望在三分之一的案例中使用每个if
语句,则应使用值{{ 1}}和30
代替60
和33
。