다음을 통해 공유


Random.Next 메서드

정의

임의의 정수를 반환합니다.

오버로드

Next()

음수가 아닌 임의의 정수를 반환합니다.

Next(Int32)

지정된 최댓값보다 작은 음수가 아닌 임의의 정수를 반환합니다.

Next(Int32, Int32)

지정된 범위 내의 임의의 정수를 반환합니다.

Next()

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

음수가 아닌 임의의 정수를 반환합니다.

public:
 virtual int Next();
public virtual int Next ();
abstract member Next : unit -> int
override this.Next : unit -> int
Public Overridable Function Next () As Integer

반환

Int32.MaxValue보다 크거나 같고 0보다 작은 32비트 부인 정수입니다.

예제

다음 예제에서는 메서드를 반복적으로 호출하여 Next 사용자가 요청한 특정 수의 난수를 생성합니다. 메서드는 Console.ReadLine 고객 입력을 가져오는 데 사용됩니다.

using namespace System;

void main()
{
   Console::Write("Number of random numbers to generate: ");
   String^ line = Console::ReadLine();
   unsigned int numbers = 0;
   Random^ rnd = gcnew Random();
   
   if (! UInt32::TryParse(line, numbers))
      numbers = 10;
   
   for (unsigned int ctr = 1; ctr <= numbers; ctr++)
      Console::WriteLine("{0,15:N0}", rnd->Next());
}
// The example displays output like the following when asked to generate
// 15 random numbers:
//       Number of random numbers to generate: 15
//         1,733,189,596
//           566,518,090
//         1,166,108,546
//         1,931,426,514
//         1,341,108,291
//         1,012,698,049
//           890,578,409
//         1,377,589,722
//         2,108,384,181
//         1,532,939,448
//           762,207,767
//           815,074,920
//         1,521,208,785
//         1,950,436,671
//         1,266,596,666
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
let rnd = Random()

printfn "Generating 10 random numbers:"

for _ = 1 to 10 do
    printfn $"{rnd.Next(),15:N0}"

// The example displays output like the following:
//
//     Generating 10 random numbers:
//         1,733,189,596
//           566,518,090
//         1,166,108,546
//         1,931,426,514
//         1,532,939,448
//           762,207,767
//           815,074,920
//         1,521,208,785
//         1,950,436,671
//         1,266,596,666
Module Example
   Public Sub Main()
      Console.Write("Number of random numbers to generate: ")
      Dim line As String = Console.ReadLine()
      Dim numbers As UInteger = 0
      Dim rnd As New Random()
      
      If Not UInt32.TryParse(line, numbers) Then numbers = 10
      
      For ctr As UInteger = 1 To numbers  
         Console.WriteLine("{0,15:N0}", rnd.Next())
      Next
   End Sub
End Module
' The example displays output like the following when asked to generate
' 15 random numbers:
'       Number of random numbers to generate: 15
'         1,733,189,596
'           566,518,090
'         1,166,108,546
'         1,931,426,514
'         1,341,108,291
'         1,012,698,049
'           890,578,409
'         1,377,589,722
'         2,108,384,181
'         1,532,939,448
'           762,207,767
'           815,074,920
'         1,521,208,785
'         1,950,436,671
'         1,266,596,666

다음 예제에서는 에서 클래스를 파생하여 기본 클래스 Random 의 메서드에 의해 Sample 생성된 균일한 분포와 분포가 다른 난수 시퀀스를 생성합니다. 메서드를 Sample 재정의하여 난수 분포를 제공하고 메서드를 재정 Random.Next 의하여 일련의 난수를 사용합니다.

using namespace System;

// This derived class converts the uniformly distributed random 
// numbers generated by base.Sample() to another distribution.
public ref 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:
   virtual double Sample() override
   {
       return Math::Sqrt(Random::Sample());
   }

public:
   RandomProportional()
   {}
   
   virtual int Next() override
   {
      return (int) (Sample() * Int32::MaxValue);
   }   
};

int main(array<System::String ^> ^args)
{
      const int rows = 4, cols = 6;
      const int runCount = 1000000;
      const int distGroupCount = 10;
      const double intGroupSize = 
         ((double) Int32::MaxValue + 1.0) / (double)distGroupCount;

      RandomProportional ^randObj = gcnew RandomProportional();

      array<int>^ intCounts = gcnew array<int>(distGroupCount);
      array<int>^ realCounts = gcnew array<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 ]);
      return 0;
}

/*
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
*/
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
*/
' This derived class converts the uniformly distributed random 
' numbers generated by base.Sample() to another distribution.
Public Class RandomProportional
   Inherits Random

   ' The Sample method generates a distribution proportional to the value 
   ' of the random numbers, in the range [0.0, 1.0].
   Protected Overrides Function Sample() As Double
      Return Math.Sqrt(MyBase.Sample())
   End Function
   
   Public Overrides Function [Next]() As Integer
      Return Sample() * Integer.MaxValue
   End Function 
End Class 

Module RandomSampleDemo
    Sub Main()
        Const rows As Integer = 4, cols As Integer = 6
        Const runCount As Integer = 1000000
        Const distGroupCount As Integer = 10
        Const intGroupSize As Double = _
            (CDbl(Integer.MaxValue) + 1.0) / _
            CDbl(distGroupCount)
            
        Dim randObj As New RandomProportional()
            
        Dim intCounts(distGroupCount) As Integer
        Dim realCounts(distGroupCount) As Integer
        Dim i As Integer, j As Integer 
            
        Console.WriteLine(vbCrLf & _
            "The derived RandomProportional class overrides " & _ 
            "the Sample method to " & vbCrLf & _
            "generate random numbers in the range " & _ 
            "[0.0, 1.0]. The distribution " & vbCrLf & _
            "of the numbers is proportional to their numeric " & _
            "values. For example, " & vbCrLf & _ 
            "numbers are generated in the vicinity of 0.75 " & _
            "with three times " & vbCrLf & "the " & _
            "probability of those generated near 0.25.")
        Console.WriteLine(vbCrLf & _
            "Random doubles generated with the NextDouble() " & _ 
            "method:" & vbCrLf)
            
        ' Generate and display [rows * cols] random doubles.
        For i = 0 To rows - 1
            For j = 0 To cols - 1
                Console.Write("{0,12:F8}", randObj.NextDouble())
            Next j
            Console.WriteLine()
        Next i
            
        Console.WriteLine(vbCrLf & _
            "Random integers generated with the Next() " & _ 
            "method:" & vbCrLf)
            
        ' Generate and display [rows * cols] random integers.
        For i = 0 To rows - 1
            For j = 0 To cols - 1
                Console.Write("{0,12}", randObj.Next())
            Next j
            Console.WriteLine()
        Next i
            
        Console.WriteLine(vbCrLf & _
            "To demonstrate the proportional distribution, " & _ 
            "{0:N0} random " & vbCrLf & _
            "integers and doubles are grouped into {1} " & _ 
            "equal value ranges. This " & vbCrLf & _
            "is the count of values in each range:" & vbCrLf, _
            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 i = 0 To runCount - 1
            intCounts(Fix(CDbl(randObj.Next()) / _
                intGroupSize)) += 1
            realCounts(Fix(randObj.NextDouble() * _
                CDbl(distGroupCount))) += 1
        Next i
            
        ' Display the count of each group.
        For i = 0 To distGroupCount - 1
            Console.WriteLine( _
                "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}", _
                Fix(CDbl(i) * intGroupSize), _
                Fix(CDbl(i + 1) * intGroupSize - 1.0), _
                intCounts(i), _
                CDbl(i) / CDbl(distGroupCount), _
                CDbl(i + 1) / CDbl(distGroupCount), _
                realCounts(i))
        Next i
    End Sub
End Module 
' This example of Random.Sample() generates 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 their numeric 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.28377004  0.75920598  0.33430371  0.66720626  0.97080243  0.27353772
'      0.17787962  0.54618410  0.08145080  0.56286100  0.99002910  0.64898614
'      0.27673277  0.99455281  0.93778966  0.76162002  0.70533771  0.44375798
'      0.55939883  0.87383136  0.66465779  0.77392566  0.42393411  0.82409159
'    
'    Random integers generated with the Next() method:
'    
'      1364479914  1230312341  1657373812  1526222928   988564704   700078020
'      1801013705  1541517421  1146312560   338318389  1558995993  2027260859
'       884520932  1320070465   570200106  1027684711   943035246  2088689333
'       630809089  1705728475  2140787648  2097858166  1863010875  1386804198
'    
'    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     9,892     0.00000-0.10000     9,928
'     214748364- 429496728    30,341     0.10000-0.20000    30,101
'     429496729- 644245093    49,958     0.20000-0.30000    49,964
'     644245094- 858993458    70,099     0.30000-0.40000    70,213
'     858993459-1073741823    90,801     0.40000-0.50000    89,553
'    1073741824-1288490187   109,699     0.50000-0.60000   109,427
'    1288490188-1503238552   129,438     0.60000-0.70000   130,339
'    1503238553-1717986917   149,886     0.70000-0.80000   150,000
'    1717986918-1932735282   170,338     0.80000-0.90000   170,128
'    1932735283-2147483647   189,548     0.90000-1.00000   190,347

설명

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() 해야 합니다.

추가 정보

적용 대상

Next(Int32)

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

지정된 최댓값보다 작은 음수가 아닌 임의의 정수를 반환합니다.

public:
 virtual int Next(int maxValue);
public virtual int Next (int maxValue);
abstract member Next : int -> int
override this.Next : int -> int
Public Overridable Function Next (maxValue As Integer) As Integer

매개 변수

maxValue
Int32

생성될 난수의 상한(제외)입니다. maxValue는 0보다 크거나 같아야 합니다.

반환

0보다 크거나 같고 maxValue보다 작은 부호 있는 32비트 정수이므로 반환 값의 범위에는 대개 0이 포함되지만 maxValue는 포함되지 않습니다. 그러나 가 0이면 maxValue 0이 반환됩니다.

예외

maxValue 가 0보다 작습니다.

예제

다음 예제에서는 메서드의 다양한 오버로드를 사용하여 임의 Next 정수를 생성합니다.

// Example of the Random::Next() methods.
using namespace System;

// Generate random numbers with no bounds specified.
void NoBoundsRandoms(int seed)
{
   Console::WriteLine("\nRandom object, seed = {0}, no bounds:", seed);
   Random^ randObj = gcnew Random(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 = gcnew Random(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 = gcnew Random(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();
}

int main()
{
   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, Int32::MaxValue);
   UpperBoundRandoms(234, 2000000000);
   UpperBoundRandoms(234, 200000000);
   BothBoundsRandoms(234, 0, Int32::MaxValue);
   BothBoundsRandoms(234, Int32::MinValue, Int32::MaxValue);
   BothBoundsRandoms(234, -2000000000, 2000000000);
   BothBoundsRandoms(234, -200000000, 200000000);
   BothBoundsRandoms(234, -2000, 2000);
}

/*
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
*/
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
*/
let noBoundsRandoms seed =
    printfn "\nRandom object, seed = %i, no bounds:" seed
    let randObj = Random seed

    // Generate six random integers from 0 to int.MaxValue.
    for _ = 1 to 6 do
        printf $"%11i{randObj.Next()} "
    printfn ""

// Generate random numbers with an upper bound specified.
let upperBoundRandoms seed upper = 
    printfn $"\nRandom object, seed = %i{seed}, upper bound = %i{upper}"
    let randObj = Random seed

    // Generate six random integers from 0 to the upper bound.
    for _ = 1 to 6 do
        printf $"%11i{randObj.Next upper} "
    printfn ""

// Generate random numbers with both bounds specified.
let bothBoundRandoms seed lower upper =
    printfn $"\nRandom object, seed = %i{seed}, lower = %i{lower}, upper = %i{upper}: "
    let randObj = Random seed

    // Generate six random integers from the lower to upper bounds.
    for _ = 1 to 6 do 
        printf $"%11i{randObj.Next(lower,upper)} "
    printfn ""

printfn "This example of the Random.Next() methods\ngenerates the following.\n"

printfn """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."""

noBoundsRandoms 234

upperBoundRandoms 234 Int32.MaxValue
upperBoundRandoms 234 2000000000
upperBoundRandoms 234 200000000

bothBoundRandoms 234 0 Int32.MaxValue
bothBoundRandoms 234 Int32.MinValue Int32.MaxValue
bothBoundRandoms 234 -2000000000 2000000000
bothBoundRandoms 234 -200000000 200000000
bothBoundRandoms 234 -2000 2000

(*
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
*)
' Example of the Random.Next() methods.
Module RandomNextDemo

    ' Generate random numbers with no bounds specified.
    Sub NoBoundsRandoms(seed As Integer)

        Console.WriteLine(vbCrLf &
            "Random object, seed = {0}, no bounds:", seed)
        Dim randObj As New Random(seed)

        ' Generate six random integers from 0 to int.MaxValue.
        Dim j As Integer
        For j = 0 To 5
            Console.Write("{0,11} ", randObj.Next())
        Next j
        Console.WriteLine()
    End Sub

    ' Generate random numbers with an upper bound specified.
    Sub UpperBoundRandoms(seed As Integer, upper As Integer)

        Console.WriteLine(vbCrLf &
            "Random object, seed = {0}, upper bound = {1}:",
            seed, upper)
        Dim randObj As New Random(seed)

        ' Generate six random integers from 0 to the upper bound.
        Dim j As Integer
        For j = 0 To 5
            Console.Write("{0,11} ", randObj.Next(upper))
        Next j
        Console.WriteLine()
    End Sub

    ' Generate random numbers with both bounds specified.
    Sub BothBoundsRandoms(seed As Integer, lower As Integer, upper As Integer)

        Console.WriteLine(vbCrLf &
            "Random object, seed = {0}, lower = {1}, " &
            "upper = {2}:", seed, lower, upper)
        Dim randObj As New Random(seed)

        ' Generate six random integers from the lower to 
        ' upper bounds.
        Dim j As Integer
        For j = 0 To 5
            Console.Write("{0,11} ",
                randObj.Next(lower, upper))
        Next j
        Console.WriteLine()
    End Sub

    Sub Main()
        Console.WriteLine(
            "This example of the Random.Next() methods" &
            vbCrLf & "generates the following output." & vbCrLf)
        Console.WriteLine(
            "Create Random objects all with the same seed " &
            "and generate" & vbCrLf & "sequences of numbers " &
            "with different bounds. Note the effect " & vbCrLf &
            "that the various combinations " &
            "of bounds have on the sequences.")

        NoBoundsRandoms(234)

        UpperBoundRandoms(234, Int32.MaxValue)
        UpperBoundRandoms(234, 2000000000)
        UpperBoundRandoms(234, 200000000)

        BothBoundsRandoms(234, 0, Int32.MaxValue)
        BothBoundsRandoms(234, Int32.MinValue, Int32.MaxValue)
        BothBoundsRandoms(234, -2000000000, 2000000000)
        BothBoundsRandoms(234, -200000000, 200000000)
        BothBoundsRandoms(234, -2000, 2000)
    End Sub
End Module

' 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

다음 예제에서는 배열에서 문자열 값을 검색하기 위해 인덱스로 사용하는 임의 정수를 생성합니다. 배열의 가장 높은 인덱스가 길이보다 작기 때문에 속성 값 Array.Length 이 매개 변수로 maxValue 제공됩니다.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   array<String^>^ malePetNames = { "Rufus", "Bear", "Dakota", "Fido",
                                    "Vanya", "Samuel", "Koani", "Volodya",
                                    "Prince", "Yiska" };
   array<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]);
}
// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
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
let rnd = Random()

let malePetNames =
    [| "Rufus"; "Bear"; "Dakota"; "Fido";
        "Vanya"; "Samuel"; "Koani"; "Volodya";
        "Prince"; "Yiska" |]
let femalePetNames = 
    [| "Maggie"; "Penny"; "Saya"; "Princess";
        "Abby"; "Laila"; "Sadie"; "Olivia";
        "Starlight"; "Talla" |]

// Generate random indexes for pet names.
let mIndex = rnd.Next malePetNames.Length
let fIndex = rnd.Next femalePetNames.Length

// Display the result.
printfn "Suggested pet name of the day: "
printfn "   For a male:     %s" malePetNames.[mIndex]
printfn "   For a female:   %s" femalePetNames.[fIndex]

// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim malePetNames() As String = { "Rufus", "Bear", "Dakota", "Fido", 
                                    "Vanya", "Samuel", "Koani", "Volodya", 
                                    "Prince", "Yiska" }
      Dim femalePetNames() As String = { "Maggie", "Penny", "Saya", "Princess", 
                                         "Abby", "Laila", "Sadie", "Olivia", 
                                         "Starlight", "Talla" }                                      
      
      ' Generate random indexes for pet names.
      Dim mIndex As Integer = rnd.Next(malePetNames.Length)
      Dim fIndex As Integer = 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))
   End Sub
End Module
' 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에서 1까지의 임의 정수를 maxValue 반환합니다. 그러나 가 0이면 maxValue 메서드는 0을 반환합니다.

추가 정보

적용 대상

Next(Int32, Int32)

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

지정된 범위 내의 임의의 정수를 반환합니다.

public:
 virtual int Next(int minValue, int maxValue);
public virtual int Next (int minValue, int maxValue);
abstract member Next : int * int -> int
override this.Next : int * int -> int
Public Overridable Function Next (minValue As Integer, maxValue As Integer) As Integer

매개 변수

minValue
Int32

반환되는 난수의 하한(포함)입니다.

maxValue
Int32

반환되는 난수의 상한(제외)입니다. maxValueminValue보다 크거나 같아야 합니다.

반환

minValue보다 크거나 같고 maxValue보다 작은 부호 있는 32비트 정수이므로 반환 값의 범위에는 minValue가 포함되지만 maxValue는 포함되지 않습니다. minValuemaxValue와 같은 경우에는 minValue가 반환됩니다.

예외

minValuemaxValue보다 큰 경우

예제

다음 예제에서는 메서드를 Random.Next(Int32, Int32) 사용하여 세 가지 고유 범위의 임의 정수를 생성합니다. 예제의 정확한 출력은 클래스 생성자에 전달된 시스템 제공 시드 값에 Random 따라 달라집니다.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();

   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
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
let rnd = Random()

printfn "\n20 random integers from -100 to 100:"
for i = 1 to 20 do 
    printf "%6i" (rnd.Next(-100,100))
    if i % 5 = 0 then printfn ""

printfn "\n20 random integers from 1000 to 10000:"
for i = 1 to 20 do 
    printf "%8i" (rnd.Next(1000,10001))
    if i % 5 = 0 then printfn ""

printfn "\n20 random integers from 1 to 10:"
for i = 1 to 20 do 
    printf "%6i" (rnd.Next(1,11))
    if i % 5 = 0 then printfn ""

// 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
Module Example
   Public Sub Main()
      Dim rnd As New Random()

      Console.WriteLine("20 random integers from -100 to 100:")
      For ctr As Integer = 1 To 20
         Console.Write("{0,6}", rnd.Next(-100, 101))
         If ctr Mod 5 = 0 Then Console.WriteLine()
      Next
      Console.WriteLine()
      
      Console.WriteLine("20 random integers from 1000 to 10000:")      
      For ctr As Integer = 1 To 20
         Console.Write("{0,8}", rnd.Next(1000, 10001))
         If ctr Mod 5 = 0 Then Console.WriteLine()
      Next
      Console.WriteLine()
      
      Console.WriteLine("20 random integers from 1 to 10:")
      For ctr As Integer = 1 To 20
         Console.Write("{0,6}", rnd.Next(1, 11))
         If ctr Mod 5 = 0 Then Console.WriteLine()
      Next
   End Sub
End Module
' 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

다음 예제에서는 배열에서 문자열 값을 검색하기 위해 인덱스로 사용하는 임의 정수를 생성합니다. 배열의 가장 높은 인덱스가 길이보다 작기 때문에 속성 값 Array.Length 이 매개 변수로 maxValue 제공됩니다.

using namespace System;

void main()
{
   Random^ rnd = gcnew Random();
   array<String^>^ malePetNames = { "Rufus", "Bear", "Dakota", "Fido",
                                    "Vanya", "Samuel", "Koani", "Volodya",
                                    "Prince", "Yiska" };
   array<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]);
}
// The example displays the following output:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
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
let rnd = Random()

let malePetNames =
    [| "Rufus"; "Bear"; "Dakota"; "Fido";
        "Vanya"; "Samuel"; "Koani"; "Volodya";
        "Prince"; "Yiska" |]
let femalePetNames = 
    [| "Maggie"; "Penny"; "Saya"; "Princess";
        "Abby"; "Laila"; "Sadie"; "Olivia";
        "Starlight"; "Talla" |]

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

// Display the result.
printfn "Suggested pet name of the day: "
printfn "   For a male:     %s" malePetNames.[mIndex]
printfn "   For a female:   %s" femalePetNames.[fIndex]

// The example displays output similar to the following:
//       Suggested pet name of the day:
//          For a male:     Koani
//          For a female:   Maggie
Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim malePetNames() As String = { "Rufus", "Bear", "Dakota", "Fido", 
                                    "Vanya", "Samuel", "Koani", "Volodya", 
                                    "Prince", "Yiska" }
      Dim femalePetNames() As String = { "Maggie", "Penny", "Saya", "Princess", 
                                         "Abby", "Laila", "Sadie", "Olivia", 
                                         "Starlight", "Talla" }                                      
      
      ' Generate random indexes for pet names.
      Dim mIndex As Integer = rnd.Next(0, malePetNames.Length)
      Dim fIndex As Integer = 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))
   End Sub
End Module
' The example displays output like the following:
'       Suggested pet name of the day:
'          For a male:     Koani
'          For a female:   Maggie

설명

Next(Int32, Int32) 오버로드는 에서 1까지의 임 minValue 의 정수를 maxValue 반환합니다. 그러나 가 이minValuemaxValue 메서드는 를 반환합니다minValue.

음수가 아닌 값만 반환하는 메서드의 다른 오버로드와 달리 이 메서드는 음수 임의 Next 정수를 반환할 수 있습니다.

상속자 참고

.NET Framework 버전 2.0부터 클래스를 Random 파생하고 메서드를 재정 Sample() 의하는 경우 및 매개 변수 간의 minValuemaxValue 차이가 Int32.MaxValue보다 큰 경우 메서드의 Sample() 파생 클래스 구현에서 제공하는 배포는 메서드 오버로드의 Next(Int32, Int32) 기본 클래스 구현에 대한 호출에서 사용되지 않습니다. 대신 기본 Random 클래스에서 반환된 균일한 분포가 사용됩니다. 이 동작은 클래스의 Random 전반적인 성능을 향상시킵니다. 파생 클래스에서 메서드를 Sample() 호출하도록 이 동작을 수정하려면 메서드 오버로드도 재정의 Next(Int32, Int32) 해야 합니다.

추가 정보

적용 대상