這篇文章主要介紹了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(); } }}
產生無重複的隨機數
運行結果如下: