C#中Random.Next 方法

发布时间:2024年01月07日

目录

一、重载

二、Next()

1.定义

2.示例

三、Next(Int32)

1.定义?

2.示例1

3.示例2

四、Next(Int32, Int32)

1.定义

2.示例1

3.示例2


一、重载

????????返回一个随机整数。

Next()返回一个非负随机整数。
Next(Int32)返回一个小于所指定最大值的非负随机整数。
Next(Int32, Int32)返回在指定范围内的任意整数。

二、Next()

????????返回一个非负随机整数。

1.定义

public virtual int Next ();

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

2.示例

//Next()
namespace ConsoleApp39
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);

            Random rnd = new();

            Console.WriteLine("Generating 10 random numbers:");

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

// 运行结果:
/*
 Generating 10 random numbers:
  1,346,240,124
    723,453,914
  1,735,589,449
  1,860,966,112
  1,562,174,739
     22,804,240
    576,594,210
  1,204,251,909
  1,436,476,117
    828,029,130
 */

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

三、Next(Int32)

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

1.定义?

public virtual int Next (int maxValue);

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

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

例外
ArgumentOutOfRangeException
maxValue 小于 0。

2.示例1

// Next(Int32)
namespace ConsoleApp40
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);

            Console.WriteLine(
                "This example of the Random.Next() methods\n" +
                "generates the following output.\n");
            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 = {0}, no bounds:", seed);
                Random randObj = new(seed);

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

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

                // Generate six random integers from 0 to the upper bound.
                for (int j = 0; j < 6; j++)
                    Console.Write("{0,11} ", randObj.Next(upper));
                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("{0,11} ",
                        randObj.Next(lower, upper));
                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
*/

3.示例2

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

// Next(Int32)
namespace ConsoleApp41
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            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:     {0}", malePetNames[mIndex]);
            Console.WriteLine("   For a female:   {0}", femalePetNames[fIndex]);
        }
    }
}

// 运行结果:
/*
Suggested pet name of the day:
   For a male:     Samuel
   For a female:   Abby
*/

四、Next(Int32, Int32)

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

1.定义

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

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

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

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

例外
ArgumentOutOfRangeException
minValue 大于 maxValue。

????????重载 Next(Int32, Int32) 返回范围从 minValue 到 maxValue - 1 的随机整数。 但是,如果 maxValue 等于 minValue,则 方法返回 minValue。与仅返回非负值的方法的其他重载 Next 不同,此方法可以返回负随机整数。?

2.示例1

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

// Next(Int32, Int32)
namespace ConsoleApp42
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);

            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();
            }
        }
    }
}

// 运行结果:
/*
20 random integers from -100 to 100:
   -78   -13    58   -11    80
   -49    -5   -57    81   -44
    69    28   -63   -23    65
    96   -20   -37    76    18

20 random integers from 1000 to 10000:
    3738    6382    4790    2334    1875
    6557    6491    2583    2012    6601
    5929    4639    7814    3045    1737
    5512    4275    8866    2288    7201

20 random integers from 1 to 10:
     4     7     1     5     7
     2     7     6     3     4
    10     6     3     3     7
     1     3     1    10     6

 */

3.示例2

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

// Next(Int32, Int32)
namespace ConsoleApp43
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            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:     {0}", malePetNames[mIndex]);
            Console.WriteLine("   For a female:   {0}", femalePetNames[fIndex]);
        }
    }
}

// 运行结果:
/*
Suggested pet name of the day:
   For a male:     Samuel
   For a female:   Penny
 */

文章来源:https://blog.csdn.net/wenchm/article/details/135443077
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。