Home  >  Article  >  Backend Development  >  Detailed code example of C# generating random number function

Detailed code example of C# generating random number function

黄舟
黄舟Original
2017-03-29 11:49:021708browse

This article mainly introduces the function of generating random numbers in C#, involving techniques related to C# mathematical operations and string operations. It has certain reference value. Friends who need it can refer to it.

The example in this article describes the function of generating random numbers in C#. Share it with everyone for your reference, the details are as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace csharp
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("生成随机数\n");
      int randCount = 9;//随机数发的个数
      int randMin = 1;//随机数最小值
      int randMax = 21;//随机数最大值
      int randIndex, flag, temp;
      randIndex = temp = flag = 0;
      Random rand = new Random();
      int[] randArr = new int[randCount];
      randArr[0] = rand.Next(randMin, randMax);
      while (true)
      {
        flag = 0;
        temp = rand.Next(randMin, randMax);
        for (int i = 0; i <= randIndex; i++)
        {
          if (temp == randArr[i])
          {
            flag = 1;
            break;
          }
        }
        if (flag == 1)//如果 flag == 1 则有重复的数字生成。
        {
          continue;
        }
        else if (flag == 0)
        {
          randIndex++;
          randArr[randIndex] = temp;
        }
        if (randIndex >= randCount - 1)//如果达到 randCount 退出循环
        {
          break;
        }
      }
      for (int i = 0; i < randCount; i++)
      {
        Console.WriteLine("arr[" + i + "]=" + randArr[i]);
      }
      Console.WriteLine("\n任意键退出。");
      Console.ReadLine();
    }
  }
}

Generate random numbers without duplication

The running results are as follows:

The above is the detailed content of Detailed code example of C# generating random number function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn