C#生成隨機數(shù)功能示例
更新時間:2017年01月16日 11:37:38 作者:lx_3278@126
這篇文章主要介紹了C#生成隨機數(shù)功能,涉及C#數(shù)學(xué)運算與字符串操作相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#生成隨機數(shù)功能。分享給大家供大家參考,具體如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace csharp { class Program { static void Main(string[] args) { Console.WriteLine("生成隨機數(shù)\n"); int randCount = 9;//隨機數(shù)發(fā)的個數(shù) int randMin = 1;//隨機數(shù)最小值 int randMax = 21;//隨機數(shù)最大值 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 則有重復(fù)的數(shù)字生成。 { continue; } else if (flag == 0) { randIndex++; randArr[randIndex] = temp; } if (randIndex >= randCount - 1)//如果達到 randCount 退出循環(huán) { break; } } for (int i = 0; i < randCount; i++) { Console.WriteLine("arr[" + i + "]=" + randArr[i]); } Console.WriteLine("\n任意鍵退出。"); Console.ReadLine(); } } }
生成無重復(fù)的隨機數(shù)
運行結(jié)果如下:
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#窗體操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#程序設(shè)計之線程使用技巧總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#數(shù)組操作技巧總結(jié)》及《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》
希望本文所述對大家C#程序設(shè)計有所幫助。