azz*_*idz 11 c# asp.net random
我需要一些C#代码有机会的帮助.假设我有从1到100的循环,并且在该循环中我有一个"if"代码,我想要执行70%(随机).我怎么做到这一点?所以像这样:
static void Main(string[] args)
{
var clickPercentage = 70;
for (int i = 0; i < 100; i++)
{
if (chance)
{
//do 70% times
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,对于顶级示例,我希望如果代码被击中的可能性为70%,对于我的示例大约为70次.
我试过的事情:(远不及70%,更像是1%或2%的几率)
static void Main(string[] args)
{
var clickPercentage = 70;
for (int i = 0; i < 100; i++)
{
var a = GetRadnomNumber(1, clickPercentage);
var b = GetRadnomNumber(1, 101);
if (a <= b)
{
Console.WriteLine($"Iteracija {i} - {b} <= {a}");
}
}
}
public static int GetRadnomNumber(int min, int max)
{
var random = new Random();
var retVal = random.Next(min, max);
return retVal;
}
Run Code Online (Sandbox Code Playgroud)
使用该Random课程.
您可以使用0到99之间Random.Next(100) 的随机int值:
public static Random RandomGen = new Random();
.....
int clickPercentage = 70;
for (int i = 0; i < 100; i++)
{
int randomValueBetween0And99 = RandomGen.Next(100);
if (randomValueBetween0And99 < clickPercentage)
{
//do 70% times
}
}
Run Code Online (Sandbox Code Playgroud)
重要的是不要在循环中创建随机实例,因为它的默认构造函数使用当前时间作为种子.这可能会导致循环中的重复值.这就是为什么我使用了一个static领域.您还可以将Random实例传递给方法,以确保调用者负责生命周期和种子.有时使用相同的种子很重要,例如重复相同的测试.
小智 5
将其包装为一个函数:
private static Random generator = null;
/*
* Calls onSuccess() chanceOfSuccess% of the time, otherwise calls onFailure()
*/
public void SplitAtRandom(int chanceOfSuccess, Action onSuccess, Action onFailure)
{
// Seed
if (generator == null)
generator = new Random(DateTime.Now.Millisecond);
// By chance
if (generator.Next(100) < chanceOfSuccess)
{
if (onSuccess != null)
onSuccess();
}
else
{
if (onFailure != null)
onFailure();
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它:
for (int i = 0; i < 100; i++)
{
SplitAtRandom(70,
() => { /* 70% of the time */ },
() => { /* 30% of the time */ });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2361 次 |
| 最近记录: |