如何使用随机方法多次掷骰子而不会获得相同的结果?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DieRoller
{
public class Program
{
public static void Main()
{
for (int a = 0; a < 20; a = a + 1)
{
Console.WriteLine(RollDie());
}
Console.ReadLine();
}
public static int RollDie()
{
Random roll = new Random();
int test = roll.Next(1, 6 + 1);
return test;
}
}
}

当我执行此代码时,我多次得到数字 4 或多次得到数字 2......等。

它不是应该为循环的每次迭代执行 RollDie 函数吗? 这不是应该每次产生不同的值吗? 请哈尔普!

编辑:问题是伙计们,我只需要在 RollDie 方法中生成随机性,并且我不能对 RollDie 方法有任何参数(基本上我必须仅使用 RollDie 方法内的随机方法生成随机性(,其他问题没有解决这个问题。

请参阅注释以了解它不起作用的原因。 这里有一种可能的方法可以使其工作:

public static void Main()
{
Random roll = new Random();
for (int a = 0; a < 20; a = a + 1)
{
Console.WriteLine(RollDie(roll));
}
Console.ReadLine();
}
public static int RollDie(Random roll)
{
int test = roll.Next(1, 6 + 1);
return test;
}

或者,为简单起见,只需:

public static void Main()
{
Random roll = new Random();
for (int a = 0; a < 20; a = a + 1)
{
Console.WriteLine(roll.Next(1, 6 + 1));
}
Console.ReadLine();
}

最新更新