C# 如何使用随机方法多次掷骰子而不获得相同的结果? 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 压路机 { 公共课程 { 公共静态void Main() { 对于(int a=0;a
当我执行这段代码时,我多次得到数字4或数字2…等等 它不是应该为循环的每个迭代执行RollDie函数吗?这不是每次都会产生不同的值吗?请停下来C# 如何使用随机方法多次掷骰子而不获得相同的结果? 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 压路机 { 公共课程 { 公共静态void Main() { 对于(int a=0;a,c#,C#,当我执行这段代码时,我多次得到数字4或数字2…等等 它不是应该为循环的每个迭代执行RollDie函数吗?这不是每次都会产生不同的值吗?请停下来 编辑:伙计们,我只需要在RollDie方法中生成随机性,我不能为RollDie方法提供任何参数(基本上我只需要在RollDie方法中使用random方法生成随机性),其他问题不能解决这个问题。请参阅注释以了解为什么它不起作用。以下是一种可行的方法: using System; using System.Collections.Generic; using
编辑:伙计们,我只需要在RollDie方法中生成随机性,我不能为RollDie方法提供任何参数(基本上我只需要在RollDie方法中使用random方法生成随机性),其他问题不能解决这个问题。请参阅注释以了解为什么它不起作用。以下是一种可行的方法:
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;
}
}
}
publicstaticvoidmain()
{
随机滚动=新随机();
对于(int a=0;a<20;a=a+1)
{
控制台写入线(滚动模(滚动));
}
Console.ReadLine();
}
公共静态int RollDie(随机滚动)
{
int测试=滚动下一步(1,6+1);
回归试验;
}
或者,为了简单起见,只需:
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;
}
publicstaticvoidmain()
{
随机滚动=新随机();
对于(int a=0;a<20;a=a+1)
{
控制台写入线(滚动下一个(1,6+1));
}
Console.ReadLine();
}
当您快速连续创建新的Random实例时,它们通常会以相同的种子结束,从而产生相同的值。
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();
}