Random.Next 方法

定义

返回一个随机整数。

重载

Next()

返回一个非负随机整数。

Next(Int32)

返回一个小于所指定最大值的非负随机整数。

Next(Int32, Int32)

返回在指定范围内的任意整数。

Next()

Source:
Random.cs
Source:
Random.cs
Source:
Random.cs

返回一个非负随机整数。

C#
public virtual int Next ();

返回

大于或等于 0 且小于 Int32.MaxValue 的 32 位有符号整数。

示例

以下示例对 方法进行重复调用, Next 以生成用户请求的特定数量的随机数。 方法 Console.ReadLine 用于获取客户输入。

C#
Console.Write("Number of random numbers to generate: ");

string? line = Console.ReadLine();
Random rnd = new Random();

if (!int.TryParse(line, out int numbers) || numbers <= 0)
{
    numbers = 10;
}

for (uint ctr = 1; ctr <= numbers; ctr++)
    Console.WriteLine($"{rnd.Next(),15:N0}");

// The example displays output like the following when asked to generate
// 15 random numbers:
// Number of random numbers to generate: 15
//     367 920 603
//   1 143 790 667
//   1 360 963 275
//   1 851 697 775
//     248 956 796
//   1 009 615 458
//   1 617 743 155
//   1 821 609 652
//   1 661 761 949
//     477 300 794
//     288 418 129
//     425 371 492
//   1 558 147 880
//   1 473 704 017
//     777 507 489

以下示例从 Random 派生类,以生成一个随机数序列,该序列的分布不同于基类 的 方法生成的 Sample 统一分布。 它替代 Sample 方法以提供随机数的分布,并重写 Random.Next 方法以使用随机数系列。

C#
using System;

// This derived class converts the uniformly distributed random
// numbers generated by base.Sample() to another distribution.
public class RandomProportional : Random
{
    // The Sample method generates a distribution proportional to the value
    // of the random numbers, in the range [0.0, 1.0].
    protected override double Sample()
    {
        return Math.Sqrt(base.Sample());
    }

    public override int Next()
    {
       return (int) (Sample() * int.MaxValue);
    }
}

public class RandomSampleDemo
{
    static void Main()
    {	
        const int rows = 4, cols = 6;
        const int runCount = 1000000;
        const int distGroupCount = 10;
        const double intGroupSize =
            ((double)int.MaxValue + 1.0) / (double)distGroupCount;

        RandomProportional randObj = new RandomProportional();

        int[ ]      intCounts = new int[ distGroupCount ];
        int[ ]      realCounts = new int[ distGroupCount ];

        Console.WriteLine(
            "\nThe derived RandomProportional class overrides " +
            "the Sample method to \ngenerate random numbers " +
            "in the range [0.0, 1.0]. The distribution \nof " +
            "the numbers is proportional to their numeric values. " +
            "For example, \nnumbers are generated in the " +
            "vicinity of 0.75 with three times the \n" +
            "probability of those generated near 0.25.");
        Console.WriteLine(
            "\nRandom doubles generated with the NextDouble() " +
            "method:\n");

        // Generate and display [rows * cols] random doubles.
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
                Console.Write("{0,12:F8}", randObj.NextDouble());
            Console.WriteLine();
        }

        Console.WriteLine(
            "\nRandom integers generated with the Next() " +
            "method:\n");

        // Generate and display [rows * cols] random integers.
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
                Console.Write("{0,12}", randObj.Next());
            Console.WriteLine();
        }

        Console.WriteLine(
            "\nTo demonstrate the proportional distribution, " +
            "{0:N0} random \nintegers and doubles are grouped " +
            "into {1} equal value ranges. This \n" +
            "is the count of values in each range:\n",
            runCount, distGroupCount);
        Console.WriteLine(
            "{0,21}{1,10}{2,20}{3,10}", "Integer Range",
            "Count", "Double Range", "Count");
        Console.WriteLine(
            "{0,21}{1,10}{2,20}{3,10}", "-------------",
            "-----", "------------", "-----");

        // Generate random integers and doubles, and then count
        // them by group.
        for (int i = 0; i < runCount; i++)
        {
            intCounts[ (int)((double)randObj.Next() /
                intGroupSize) ]++;
            realCounts[ (int)(randObj.NextDouble() *
                (double)distGroupCount) ]++;
        }

        // Display the count of each group.
        for (int i = 0; i < distGroupCount; i++)
            Console.WriteLine(
                "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}",
                (int)((double)i * intGroupSize),
                (int)((double)(i + 1) * intGroupSize - 1.0),
                intCounts[ i ],
                ((double)i) / (double)distGroupCount,
                ((double)(i + 1)) / (double)distGroupCount,
                realCounts[ i ]);
    }
}

/*
This example of Random.Sample() displays output similar to the following:

   The derived RandomProportional class overrides the Sample method to
   generate random numbers in the range [0.0, 1.0). The distribution
   of the numbers is proportional to the number values. For example,
   numbers are generated in the vicinity of 0.75 with three times the
   probability of those generated near 0.25.

   Random doubles generated with the NextDouble() method:

     0.59455719  0.17589882  0.83134398  0.35795862  0.91467727  0.54022658
     0.93716947  0.54817519  0.94685080  0.93705478  0.18582318  0.71272428
     0.77708682  0.95386216  0.70412393  0.86099417  0.08275804  0.79108316
     0.71019941  0.84205103  0.41685082  0.58186880  0.89492302  0.73067715

   Random integers generated with the Next() method:

     1570755704  1279192549  1747627711  1705700211  1372759203  1849655615
     2046235980  1210843924  1554274149  1307936697  1480207570  1057595022
      337854215   844109928  2028310798  1386669369  2073517658  1291729809
     1537248240  1454198019  1934863511  1640004334  2032620207   534654791

   To demonstrate the proportional distribution, 1,000,000 random
   integers and doubles are grouped into 10 equal value ranges. This
   is the count of values in each range:

           Integer Range     Count        Double Range     Count
           -------------     -----        ------------     -----
            0- 214748363    10,079     0.00000-0.10000    10,148
    214748364- 429496728    29,835     0.10000-0.20000    29,849
    429496729- 644245093    49,753     0.20000-0.30000    49,948
    644245094- 858993458    70,325     0.30000-0.40000    69,656
    858993459-1073741823    89,906     0.40000-0.50000    90,337
   1073741824-1288490187   109,868     0.50000-0.60000   110,225
   1288490188-1503238552   130,388     0.60000-0.70000   129,986
   1503238553-1717986917   149,231     0.70000-0.80000   150,428
   1717986918-1932735282   170,234     0.80000-0.90000   169,610
   1932735283-2147483647   190,381     0.90000-1.00000   189,813
*/

注解

Random.Next 生成一个随机数,其值范围为 0 到小于 Int32.MaxValue。 若要生成值范围为 0 到某个其他正数的随机数,请使用 Random.Next(Int32) 方法重载。 若要在不同的范围内生成随机数,请使用 Random.Next(Int32, Int32) 方法重载。

继承者说明

从 .NET Framework 版本 2.0 开始,如果从 Random 派生类并重写 Sample() 方法,则方法的Sample()派生类实现提供的分布不会用于调用方法的Next()基类实现。 而是使用基 Random 类返回的统一分布。 此行为可提高 类的整体性能 Random 。 若要修改此行为以调用 Sample() 派生类中的 方法,还必须重写 Next() 方法。

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Next(Int32)

Source:
Random.cs
Source:
Random.cs
Source:
Random.cs

返回一个小于所指定最大值的非负随机整数。

C#
public virtual int Next (int maxValue);

参数

maxValue
Int32

要生成的随机数的上限(随机数不能取该上限值)。 maxValue 必须大于或等于 0。

返回

大于或等于零且小于 maxValue 的 32 位有符号整数,即:返回值的范围通常包括零但不包括 maxValue。 但是,如果 maxValue 等于 0,则返回 0。

例外

maxValue 小于 0。

示例

以下示例使用 方法的各种重载 Next 生成随机整数。

C#
Console.WriteLine(
    """
    This example of the Random.Next() methods
    generates the following output.
    """
    );
Console.WriteLine(
    """
    Create Random objects all with the same seed and
    generate\nsequences of numbers with different
    bounds. Note the effect\nthat the various
    combinations of bounds have on the sequences.
    """
    );

NoBoundsRandoms(234);

UpperBoundRandoms(234, int.MaxValue);
UpperBoundRandoms(234, 2000000000);
UpperBoundRandoms(234, 200000000);

BothBoundsRandoms(234, 0, int.MaxValue);
BothBoundsRandoms(234, int.MinValue, int.MaxValue);
BothBoundsRandoms(234, -2000000000, 2000000000);
BothBoundsRandoms(234, -200000000, 200000000);
BothBoundsRandoms(234, -2000, 2000);

// Generate random numbers with no bounds specified.
void NoBoundsRandoms(int seed)
{
    Console.WriteLine(
        $"\nRandom object, seed = {seed}, no bounds:"
        );
    Random randObj = new(seed);

    // Generate six random integers from 0 to int.MaxValue.
    for (int j = 0; j < 6; j++)
        Console.Write($"{randObj.Next(),11} ");
    Console.WriteLine();
}

// Generate random numbers with an upper bound specified.
void UpperBoundRandoms(int seed, int upper)
{
    Console.WriteLine(
        $"\nRandom object, seed = {seed}, upper bound = {upper}:"
        );
    Random randObj = new(seed);

    // Generate six random integers from 0 to the upper bound.
    for (int j = 0; j < 6; j++)
        Console.Write($"{randObj.Next(upper),11} ");
    Console.WriteLine();
}

// Generate random numbers with both bounds specified.
void BothBoundsRandoms(int seed, int lower, int upper)
{
    Console.WriteLine(
        "\nRandom object, seed = {0}, lower = {1}, " +
        "upper = {2}:", seed, lower, upper);
    Random randObj = new(seed);

    // Generate six random integers from the lower to
    // upper bounds.
    for (int j = 0; j < 6; j++)
        Console.Write($"{randObj.Next(lower, upper),11} ");
    Console.WriteLine();
}

/*
This example of the Random.Next() methods
generates the following output.

Create Random objects all with the same seed and generate
sequences of numbers with different bounds. Note the effect
that the various combinations of bounds have on the sequences.

Random object, seed = 234, no bounds:
2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, upper bound = 2147483647:
2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, upper bound = 2000000000:
1947533580   954563751   662424922  1007613896  1707392518   101943116

Random object, seed = 234, upper bound = 200000000:
194753358    95456375    66242492   100761389   170739251    10194311

Random object, seed = 234, lower = 0, upper = 2147483647:
2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, lower = -2147483648, upper = 2147483647:
2034812868   -97573602  -724936960    16350718  1519113864 -1928562472

Random object, seed = 234, lower = -2000000000, upper = 2000000000:
1895067160   -90872498  -675150156    15227793  1414785036 -1796113767

Random object, seed = 234, lower = -200000000, upper = 200000000:
189506716    -9087250   -67515016     1522779   141478503  -179611377

Random object, seed = 234, lower = -2000, upper = 2000:
    1895         -91        -676          15        1414       -1797
*/

以下示例生成一个随机整数,该整数用作索引从数组中检索字符串值。 由于数组的最高索引小于其长度的 1,因此 属性的值 Array.Length 作为 maxValue 参数提供。

C#
Random rnd = new();
string[] malePetNames = [ "Rufus", "Bear", "Dakota", "Fido",
                        "Vanya", "Samuel", "Koani", "Volodya",
                        "Prince", "Yiska" ];
string[] femalePetNames = [ "Maggie", "Penny", "Saya", "Princess",
                          "Abby", "Laila", "Sadie", "Olivia",
                          "Starlight", "Talla" ];

// Generate random indexes for pet names.
int mIndex = rnd.Next(malePetNames.Length);
int fIndex = rnd.Next(femalePetNames.Length);

// Display the result.
Console.WriteLine("Suggested pet name of the day: ");
Console.WriteLine($"   For a male:     {malePetNames[mIndex]}");
Console.WriteLine($"   For a female:   {femalePetNames[fIndex]}");

// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie

注解

Next(Int32) 载返回从 0 到 maxValue - 1 的随机整数。 但是,如果 maxValue 为 0,则方法返回 0。

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Next(Int32, Int32)

Source:
Random.cs
Source:
Random.cs
Source:
Random.cs

返回在指定范围内的任意整数。

C#
public virtual int Next (int minValue, int maxValue);

参数

minValue
Int32

返回的随机数的下界(随机数可取该下界值)。

maxValue
Int32

返回的随机数的上界(随机数不能取该上界值)。 maxValue 必须大于或等于 minValue

返回

一个大于等于 minValue 且小于 maxValue 的 32 位带符号整数,即:返回的值范围包括 minValue 但不包括 maxValue。 如果 minValue 等于 maxValue,则返回 minValue

例外

minValue 大于 maxValue

示例

以下示例使用 Random.Next(Int32, Int32) 方法生成具有三个不同范围的随机整数。 请注意,此示例的确切输出取决于传递给 Random 类构造函数的系统提供的种子值。

C#
Random rnd = new();

Console.WriteLine("\n20 random integers from -100 to 100:");
for (int ctr = 1; ctr <= 20; ctr++)
{
   Console.Write("{0,6}", rnd.Next(-100, 101));
   if (ctr % 5 == 0) Console.WriteLine();
}

Console.WriteLine("\n20 random integers from 1000 to 10000:");
for (int ctr = 1; ctr <= 20; ctr++)
{
   Console.Write("{0,8}", rnd.Next(1000, 10001));
   if (ctr % 5 == 0) Console.WriteLine();
}

Console.WriteLine("\n20 random integers from 1 to 10:");
for (int ctr = 1; ctr <= 20; ctr++)
{
   Console.Write("{0,6}", rnd.Next(1, 11));
   if (ctr % 5 == 0) Console.WriteLine();
}

// The example displays output similar to the following:
//       20 random integers from -100 to 100:
//           65   -95   -10    90   -35
//          -83   -16   -15   -19    41
//          -67   -93    40    12    62
//          -80   -95    67   -81   -21
//
//       20 random integers from 1000 to 10000:
//           4857    9897    4405    6606    1277
//           9238    9113    5151    8710    1187
//           2728    9746    1719    3837    3736
//           8191    6819    4923    2416    3028
//
//       20 random integers from 1 to 10:
//            9     8     5     9     9
//            9     1     2     3     8
//            1     4     8    10     5
//            9     7     9    10     5

以下示例生成一个随机整数,该整数用作索引从数组中检索字符串值。 由于数组的最高索引小于其长度的 1,因此 属性的值 Array.Length 作为 maxValue 参数提供。

C#
Random rnd = new();
string[] malePetNames = [ "Rufus", "Bear", "Dakota", "Fido",
                        "Vanya", "Samuel", "Koani", "Volodya",
                        "Prince", "Yiska" ];
string[] femalePetNames = [ "Maggie", "Penny", "Saya", "Princess",
                          "Abby", "Laila", "Sadie", "Olivia",
                          "Starlight", "Talla" ];

// Generate random indexes for pet names.
int mIndex = rnd.Next(0, malePetNames.Length);
int fIndex = rnd.Next(0, femalePetNames.Length);

// Display the result.
Console.WriteLine("Suggested pet name of the day: ");
Console.WriteLine($"   For a male:     {malePetNames[mIndex]}");
Console.WriteLine($"   For a female:   {femalePetNames[fIndex]}");

// The example displays the following output:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie

注解

Next(Int32, Int32) 载返回范围从 minValuemaxValue - 1 的随机整数。 但是,如果 maxValue 等于 minValue,则 方法返回 minValue

与仅返回非负值的方法的其他重载 Next 不同,此方法可以返回负随机整数。

继承者说明

从 .NET Framework 版本 2.0 开始,如果从 Random 派生类并重写Sample()方法,则如果 和 maxValue 参数之间的差异大于 Int32.MaxValue,则不会在调用方法重载的Next(Int32, Int32)基类实现时minValue使用该方法的Sample()派生类实现提供的分布。 而是使用基 Random 类返回的统一分布。 此行为可提高 类的整体性能 Random 。 若要修改此行为以调用 Sample() 派生类中的 方法,还必须重写 Next(Int32, Int32) 方法重载。

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0