获取随机整数值 C#
Get Random integer value C#
为什么使用方法RandomBool()
,我总是得到1?请帮助修复第二种方法。
static class Tools
{
public static int RandomNumber(int end)
{
var rand = new Random(DateTime.Now.Millisecond);
return rand.Next(0, end);
}
public static bool RandomBool()
{
if(RandomNumber(1) == 0)
return true;
else
return false;
}
}
您应该使用此代码:
if(RandomNumber(2) == 0)
这包括 0 和 1,但不包括 2,因为随机不包括上限。
或者将 return rand.Next(0, end);
更改为 return rand.Next(0, end + 1);
这应该可以解决问题
if(RandomNumber(2) == 0) // <= Correction ; RandomNumber(2) will Return 0 OR 1
return true;
else
return false;
Random.Next 方法:(MSDN)
当您这样称呼它时,Random.Next(MinValue,MaxValue)
将应用以下规则
A 32-bit signed integer greater than or equal to minValue and less than maxValue. The range of return values includes minValue but not maxValue.
在您的情况下,您使用了 Min = 0
和 Max =1
,它们总是 return 0
.
为什么使用方法RandomBool()
,我总是得到1?请帮助修复第二种方法。
static class Tools
{
public static int RandomNumber(int end)
{
var rand = new Random(DateTime.Now.Millisecond);
return rand.Next(0, end);
}
public static bool RandomBool()
{
if(RandomNumber(1) == 0)
return true;
else
return false;
}
}
您应该使用此代码:
if(RandomNumber(2) == 0)
这包括 0 和 1,但不包括 2,因为随机不包括上限。
或者将 return rand.Next(0, end);
更改为 return rand.Next(0, end + 1);
这应该可以解决问题
if(RandomNumber(2) == 0) // <= Correction ; RandomNumber(2) will Return 0 OR 1
return true;
else
return false;
Random.Next 方法:(MSDN)
当您这样称呼它时,Random.Next(MinValue,MaxValue)
将应用以下规则
A 32-bit signed integer greater than or equal to minValue and less than maxValue. The range of return values includes minValue but not maxValue.
在您的情况下,您使用了 Min = 0
和 Max =1
,它们总是 return 0
.