首頁 後端開發 C#.Net教程 詳解C#產生隨機數函數的程式碼範例

詳解C#產生隨機數函數的程式碼範例

Mar 29, 2017 am 11:49 AM

這篇文章主要介紹了C#產生隨機數字功能,涉及C#數學運算與字串操作相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了C#產生隨機數功能。分享給大家供大家參考,具體如下:

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();
    }
  }
}
登入後複製

產生無重複的隨機數字

#運行結果如下:

以上是詳解C#產生隨機數函數的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章

兩個點博物館:邦格荒地地點指南
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章

兩個點博物館:邦格荒地地點指南
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章標籤

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

使用 C# 的活動目錄 使用 C# 的活動目錄 Sep 03, 2024 pm 03:33 PM

使用 C# 的活動目錄

C# 中的存取修飾符 C# 中的存取修飾符 Sep 03, 2024 pm 03:24 PM

C# 中的存取修飾符

C# 中的隨機數產生器 C# 中的隨機數產生器 Sep 03, 2024 pm 03:34 PM

C# 中的隨機數產生器

C# 資料網格視圖 C# 資料網格視圖 Sep 03, 2024 pm 03:32 PM

C# 資料網格視圖

C# 中的模式 C# 中的模式 Sep 03, 2024 pm 03:33 PM

C# 中的模式

C# 字串讀取器 C# 字串讀取器 Sep 03, 2024 pm 03:23 PM

C# 字串讀取器

C# 中的二進位編寫器 C# 中的二進位編寫器 Sep 03, 2024 pm 03:22 PM

C# 中的二進位編寫器

C# 字串編寫器 C# 字串編寫器 Sep 03, 2024 pm 03:23 PM

C# 字串編寫器

See all articles