当前位置: 首页>>代码示例>>C#>>正文


C# Random类代码示例

本文整理汇总了C#中System.Random的典型用法代码示例。如果您正苦于以下问题:C# Random类的具体用法?C# Random怎么用?C# Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Random类属于System命名空间,在下文中一共展示了Random类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Random

// Instantiate random number generator using system-supplied value as seed.
var rand = new Random();

// Generate and display 5 random byte (integer) values.
var bytes = new byte[5];
rand.NextBytes(bytes);
Console.WriteLine("Five random byte values:");
foreach (byte byteValue in bytes)
    Console.Write("{0, 5}", byteValue);
Console.WriteLine();   

// Generate and display 5 random integers.
Console.WriteLine("Five random integer values:");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,15:N0}", rand.Next());
Console.WriteLine();

// Generate and display 5 random integers between 0 and 100.
Console.WriteLine("Five random integers between 0 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N0}", rand.Next(101));
Console.WriteLine();

// Generate and display 5 random integers from 50 to 100.
Console.WriteLine("Five random integers between 50 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N0}", rand.Next(50, 101));
Console.WriteLine();

// Generate and display 5 random floating point values from 0 to 1.
Console.WriteLine("Five Doubles.");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N3}", rand.NextDouble());
Console.WriteLine();

// Generate and display 5 random floating point values from 0 to 5.
Console.WriteLine("Five Doubles between 0 and 5.");
for (int ctr = 0; ctr <= 4; ctr++)
    Console.Write("{0,8:N3}", rand.NextDouble() * 5);
开发者ID:.NET开发者,项目名称:System,代码行数:39,代码来源:Random

输出:

Five random byte values:
194  185  239   54  116
Five random integer values:
507,353,531  1,509,532,693  2,125,074,958  1,409,512,757    652,767,128
Five random integers between 0 and 100:
16      78      94      79      52
Five random integers between 50 and 100:
56      66      96      60      65
Five Doubles.
0.943   0.108   0.744   0.563   0.415
Five Doubles between 0 and 5.
2.934   3.130   0.292   1.432   4.369

示例2: Random

Random rnd = new Random();
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]);
开发者ID:.NET开发者,项目名称:System,代码行数:16,代码来源:Random

输出:

Suggested pet name of the day:
For a male:     Koani
For a female:   Maggie

示例3: Random

byte[] bytes1 = new byte[100];
byte[] bytes2 = new byte[100];
Random rnd1 = new Random();
Random rnd2 = new Random();

rnd1.NextBytes(bytes1);
rnd2.NextBytes(bytes2);

Console.WriteLine("First Series:");
for (int ctr = bytes1.GetLowerBound(0); 
     ctr <= bytes1.GetUpperBound(0); 
     ctr++) { 
   Console.Write("{0, 5}", bytes1[ctr]);
   if ((ctr + 1) % 10 == 0) Console.WriteLine();
} 

Console.WriteLine();

Console.WriteLine("Second Series:");        
for (int ctr = bytes2.GetLowerBound(0);
     ctr <= bytes2.GetUpperBound(0);
     ctr++) {
   Console.Write("{0, 5}", bytes2[ctr]);
   if ((ctr + 1) % 10 == 0) Console.WriteLine();
}
开发者ID:.NET开发者,项目名称:System,代码行数:25,代码来源:Random

输出:

First Series:
97  129  149   54   22  208  120  105   68  177
113  214   30  172   74  218  116  230   89   18
12  112  130  105  116  180  190  200  187  120
7  198  233  158   58   51   50  170   98   23
21    1  113   74  146  245   34  255   96   24
232  255   23    9  167  240  255   44  194   98
18  175  173  204  169  171  236  127  114   23
167  202  132   65  253   11  254   56  214  127
145  191  104  163  143    7  174  224  247   73
52    6  231  255    5  101   83  165  160  231

Second Series:
97  129  149   54   22  208  120  105   68  177
113  214   30  172   74  218  116  230   89   18
12  112  130  105  116  180  190  200  187  120
7  198  233  158   58   51   50  170   98   23
21    1  113   74  146  245   34  255   96   24
232  255   23    9  167  240  255   44  194   98
18  175  173  204  169  171  236  127  114   23
167  202  132   65  253   11  254   56  214  127
145  191  104  163  143    7  174  224  247   73
52    6  231  255    5  101   83  165  160  231

示例4: Example

//引入命名空间
using System;
using System.Threading;

public class Example
{
   [ThreadStatic] static double previous = 0.0;
   [ThreadStatic] static int perThreadCtr = 0;
   [ThreadStatic] static double perThreadTotal = 0.0;  
   static CancellationTokenSource source;
   static CountdownEvent countdown; 
   static Object randLock, numericLock;
   static Random rand;
   double totalValue = 0.0;
   int totalCount = 0;
   
   public Example()
   { 
      rand = new Random();
      randLock = new Object();
      numericLock = new Object();
      countdown = new CountdownEvent(1);
      source = new CancellationTokenSource();
   } 

   public static void Main()
   {
      Example ex = new Example();
      Thread.CurrentThread.Name = "Main";
      ex.Execute();
   }

   private void Execute()
   {   
      CancellationToken token = source.Token; 

      for (int threads = 1; threads <= 10; threads++)
      {
         Thread newThread = new Thread(this.GetRandomNumbers);
         newThread.Name = threads.ToString();
         newThread.Start(token);
      }
      this.GetRandomNumbers(token);
      
      countdown.Signal();
      // Make sure all threads have finished.
      countdown.Wait();
      source.Dispose();

      Console.WriteLine("\nTotal random numbers generated: {0:N0}", totalCount);
      Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue);
      Console.WriteLine("Random number mean: {0:N4}", totalValue/totalCount);
   }

   private void GetRandomNumbers(Object o)
   {
      CancellationToken token = (CancellationToken) o;
      double result = 0.0;
      countdown.AddCount(1);
         
      try { 
         for (int ctr = 0; ctr < 2000000; ctr++)
         {
            // Make sure there's no corruption of Random.
            token.ThrowIfCancellationRequested();

            lock (randLock) {
               result = rand.NextDouble();
            }
            // Check for corruption of Random instance.
            if ((result == previous) && result == 0) {
               source.Cancel();
            }
            else {
               previous = result;
            }
            perThreadCtr++;
            perThreadTotal += result;
         }      
       
         Console.WriteLine("Thread {0} finished execution.", 
                           Thread.CurrentThread.Name);
         Console.WriteLine("Random numbers generated: {0:N0}", perThreadCtr);
         Console.WriteLine("Sum of random numbers: {0:N2}", perThreadTotal);
         Console.WriteLine("Random number mean: {0:N4}\n", perThreadTotal/perThreadCtr);

         // Update overall totals.
         lock (numericLock) {
            totalCount += perThreadCtr;
            totalValue += perThreadTotal;  
         }
      }
      catch (OperationCanceledException e) {
         Console.WriteLine("Corruption in Thread {1}", e.GetType().Name, Thread.CurrentThread.Name);
      }
      finally {
         countdown.Signal();        
      }
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:100,代码来源:Random

输出:

Thread 6 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,491.05
Random number mean: 0.5002

Thread 10 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,329.64
Random number mean: 0.4997

Thread 4 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,166.89
Random number mean: 0.5001

Thread 8 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,628.37
Random number mean: 0.4998

Thread Main finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,920.89
Random number mean: 0.5000

Thread 3 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,370.45
Random number mean: 0.4997

Thread 7 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,330.92
Random number mean: 0.4997

Thread 9 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,172.79
Random number mean: 0.5001

Thread 5 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,079.43
Random number mean: 0.5000

Thread 1 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,817.91
Random number mean: 0.4999

Thread 2 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,930.63
Random number mean: 0.5000


Total random numbers generated: 22,000,000
Total sum of all random numbers: 10,998,238.98
Random number mean: 0.4999

示例5: Example

//引入命名空间
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   static Object randLock, numericLock;
   static Random rand;
   static CancellationTokenSource source;
   double totalValue = 0.0;
   int totalCount = 0;
   
   public Example()
   { 
      rand = new Random();
      randLock = new Object();
      numericLock = new Object();
      source = new CancellationTokenSource();
   } 

   public static async Task Main()
   {
      Example ex = new Example();
      Thread.CurrentThread.Name = "Main";
      await ex.Execute();
   }

   private Task Execute()
   {   
      List<Task> tasks = new List<Task>();
      
      for (int ctr = 0; ctr <= 10; ctr++)
      {
         CancellationToken token = source.Token; 
         int taskNo = ctr;
         tasks.Add(Task.Run( () =>
            {
               double previous = 0.0;
               int taskCtr = 0;
               double taskTotal = 0.0;  
               double result = 0.0;
                               
               for (int n = 0; n < 2000000; n++)
               {
                  // Make sure there's no corruption of Random.
                  token.ThrowIfCancellationRequested();

                  lock (randLock) {
                     result = rand.NextDouble();
                  }
                  // Check for corruption of Random instance.
                  if ((result == previous) && result == 0) {
                     source.Cancel();
                  }
                  else {
                     previous = result;
                  }
                  taskCtr++;
                  taskTotal += result;
               }

               // Show result.
               Console.WriteLine("Task {0} finished execution.", taskNo);
               Console.WriteLine("Random numbers generated: {0:N0}", taskCtr);
               Console.WriteLine("Sum of random numbers: {0:N2}", taskTotal);
               Console.WriteLine("Random number mean: {0:N4}\n", taskTotal/taskCtr);
         
               // Update overall totals.
               lock (numericLock) {
                  totalCount += taskCtr;
                  totalValue += taskTotal;  
               }
            }, 
         token));
      }
      try {
         await Task.WhenAll(tasks.ToArray());
         Console.WriteLine("\nTotal random numbers generated: {0:N0}", totalCount);
         Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue);
         Console.WriteLine("Random number mean: {0:N4}", totalValue/totalCount);
      }
      catch (AggregateException e) {
         foreach (Exception inner in e.InnerExceptions) {
            TaskCanceledException canc = inner as TaskCanceledException;
            if (canc != null)
               Console.WriteLine("Task #{0} cancelled.", canc.Task.Id);
            else
               Console.WriteLine("Exception: {0}", inner.GetType().Name);
         }         
      }
      finally {
         source.Dispose();
      }
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:97,代码来源:Random

输出:

Task 1 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,502.47
Random number mean: 0.5003

Task 0 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,445.63
Random number mean: 0.5002

Task 2 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,556.04
Random number mean: 0.5003

Task 3 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,178.87
Random number mean: 0.5001

Task 4 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,819.17
Random number mean: 0.4999

Task 5 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,190.58
Random number mean: 0.5001

Task 6 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,720.21
Random number mean: 0.4999

Task 7 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,000.96
Random number mean: 0.4995

Task 8 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,499.33
Random number mean: 0.4997

Task 9 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 1,000,193.25
Random number mean: 0.5001

Task 10 finished execution.
Random numbers generated: 2,000,000
Sum of random numbers: 999,960.82
Random number mean: 0.5000


Total random numbers generated: 22,000,000
Total sum of all random numbers: 11,000,067.33
Random number mean: 0.5000

示例6: Random

Random rnd = new Random();
Byte[] bytes = new Byte[20];
rnd.NextBytes(bytes);  
for (int ctr = 1; ctr <= bytes.Length; ctr++) {
   Console.Write("{0,3}   ", bytes[ctr - 1]);
   if (ctr % 10 == 0) Console.WriteLine();
}
开发者ID:.NET开发者,项目名称:System,代码行数:7,代码来源:Random

输出:

141    48   189    66   134   212   211    71   161    56
181   166   220   133     9   252   222    57    62    62

示例7: Random

Random rnd = new Random();
for (int ctr = 0; ctr < 10; ctr++) {
   Console.Write("{0,3}   ", rnd.Next(-10, 11));
}
开发者ID:.NET开发者,项目名称:System,代码行数:4,代码来源:Random

输出:

2     9    -3     2     4    -7    -3    -8    -8     5

示例8: Random

Random rnd = new Random();
for (int ctr = 0; ctr < 10; ctr++) {
   Console.Write("{0,-19:R}   ", rnd.NextDouble());
   if ((ctr + 1) % 3 == 0) Console.WriteLine();
}
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:Random

输出:

0.7911680553998649    0.0903414949264105    0.79776258291572455    
0.615568345233597     0.652644504165577     0.84023809378977776   
0.099662564741290441   0.91341467383942321  0.96018602045261581   
0.74772306473354022

示例9: Main

//引入命名空间
using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Instantiating two random number generators...");
      Random rnd1 = new Random();
      Thread.Sleep(2000);
      Random rnd2 = new Random();
      
      Console.WriteLine("\nThe first random number generator:");
      for (int ctr = 1; ctr <= 10; ctr++)
         Console.WriteLine("   {0}", rnd1.Next());

      Console.WriteLine("\nThe second random number generator:");
      for (int ctr = 1; ctr <= 10; ctr++)
         Console.WriteLine("   {0}", rnd2.Next());
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:22,代码来源:Random

输出:

Instantiating two random number generators...

The first random number generator:
643164361
1606571630
1725607587
2138048432
496874898
1969147632
2034533749
1840964542
412380298
47518930

The second random number generator:
1251659083
1514185439
1465798544
517841554
1821920222
195154223
1538948391
1548375095
546062716
897797880

示例10: Random

Random rnd = new Random();
for (int ctr = 1; ctr <= 15; ctr++) {
   Console.Write("{0,3}    ", rnd.Next(-10, 11));
   if(ctr % 5 == 0) Console.WriteLine();
}
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:Random

输出:

-2     -5     -1     -2     10
-3      6     -4     -8      3
-7     10      5     -2      4

示例11: Random

Random rnd = new Random();
for (int ctr = 1; ctr <= 50; ctr++) {
   Console.Write("{0,3}    ", rnd.Next(1000, 10000));
   if(ctr % 10 == 0) Console.WriteLine();
}
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:Random

输出:

9570    8979    5770    1606    3818    4735    8495    7196    7070    2313
5279    6577    5104    5734    4227    3373    7376    6007    8193    5540
7558    3934    3819    7392    1113    7191    6947    4963    9179    7907
3391    6667    7269    1838    7317    1981    5154    7377    3297    5320
9869    8694    2684    4949    2999    3019    2357    5211    9604    2593

示例12: Random

Random rnd = new Random();
for (int ctr = 1; ctr <= 10; ctr++)
   Console.WriteLine(rnd.NextDouble() - 1);
开发者ID:.NET开发者,项目名称:System,代码行数:3,代码来源:Random

输出:

-0.930412760437658
-0.164699016215605
-0.9851692803135
-0.43468508843085
-0.177202483255976
-0.776813320245972
-0.0713201854710096
-0.0912875561468711
-0.540621722368813
-0.232211863730201

示例13: Random

const long ONE_TENTH = 922337203685477581;

Random rnd = new Random();
double number;
int[] count = new int[10];

// Generate 20 million integer values between.
for (int ctr = 1; ctr <= 20000000; ctr++) {
   number = rnd.NextDouble() * Int64.MaxValue;
   // Categorize random numbers into 10 groups.
   count[(int) (number / ONE_TENTH)]++;
}
// Display breakdown by range.
Console.WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
for (int ctr = 0; ctr <= 9; ctr++)
   Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                      ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64.MaxValue, 
                      count[ctr], count[ctr]/20000000.0);
开发者ID:.NET开发者,项目名称:System,代码行数:18,代码来源:Random

输出:

Range                            Count      Pct.

0-  922,337,203,685,477,580  1,996,148    9.98 %
922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %

示例14: Random

Random rnd = new Random();
int lowerBound = 10;
int upperBound = 11;
int[] range = new int[10];
for (int ctr = 1; ctr <= 1000000; ctr++) {
   Double value = rnd.NextDouble() * (upperBound - lowerBound) + lowerBound;
   range[(int) Math.Truncate((value - lowerBound) * 10)]++; 
}

for (int ctr = 0; ctr <= 9; ctr++) {
   Double lowerRange = 10 + ctr * .1;
   Console.WriteLine("{0:N1} to {1:N1}: {2,8:N0}  ({3,7:P2})", 
                     lowerRange, lowerRange + .1, range[ctr], 
                     range[ctr] / 1000000.0);
}
开发者ID:.NET开发者,项目名称:System,代码行数:15,代码来源:Random

输出:

10.0 to 10.1:   99,929  ( 9.99 %)
10.1 to 10.2:  100,189  (10.02 %)
10.2 to 10.3:   99,384  ( 9.94 %)
10.3 to 10.4:  100,240  (10.02 %)
10.4 to 10.5:   99,397  ( 9.94 %)
10.5 to 10.6:  100,580  (10.06 %)
10.6 to 10.7:  100,293  (10.03 %)
10.7 to 10.8:  100,135  (10.01 %)
10.8 to 10.9:   99,905  ( 9.99 %)
10.9 to 11.0:   99,948  ( 9.99 %)

示例15: Main

//引入命名空间
using System;

public class Example
{
   public static void Main()
   {
      // Instantiate the Boolean generator.
      BooleanGenerator boolGen = new BooleanGenerator();
      int totalTrue = 0, totalFalse = 0;
      
      // Generate 1,0000 random Booleans, and keep a running total.
      for (int ctr = 0; ctr < 1000000; ctr++) {
          bool value = boolGen.NextBoolean();
          if (value)
             totalTrue++;
          else
             totalFalse++;
      }
      Console.WriteLine("Number of true values:  {0,7:N0} ({1:P3})", 
                        totalTrue, 
                        ((double) totalTrue)/(totalTrue + totalFalse));
      Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", 
                        totalFalse, 
                        ((double) totalFalse)/(totalTrue + totalFalse));
   }
}

public class BooleanGenerator
{
   Random rnd;
   
   public BooleanGenerator()
   {
      rnd = new Random();
   }

   public bool NextBoolean()
   {
      return Convert.ToBoolean(rnd.Next(0, 2));
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:42,代码来源:Random

输出:

Number of true values:  500,004 (50.000 %)
Number of false values: 499,996 (50.000 %)


注:本文中的System.Random类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。