C#生成隨機(jī)數(shù)功能示例
本文實(shí)例講述了C#生成隨機(jī)數(shù)功能。分享給大家供大家參考,具體如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace csharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("生成隨機(jī)數(shù)\n");
int randCount = 9;//隨機(jī)數(shù)發(fā)的個(gè)數(shù)
int randMin = 1;//隨機(jī)數(shù)最小值
int randMax = 21;//隨機(jī)數(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)//如果達(dá)到 randCount 退出循環(huán)
{
break;
}
}
for (int i = 0; i < randCount; i++)
{
Console.WriteLine("arr[" + i + "]=" + randArr[i]);
}
Console.WriteLine("\n任意鍵退出。");
Console.ReadLine();
}
}
}
生成無重復(fù)的隨機(jī)數(shù)
運(yùn)行結(jié)果如下:

更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#窗體操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#程序設(shè)計(jì)之線程使用技巧總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#數(shù)組操作技巧總結(jié)》及《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
使用C#實(shí)現(xiàn)讀取系統(tǒng)配置文件的代碼實(shí)例講解
這篇文章主要介紹了使用C#實(shí)現(xiàn)讀取系統(tǒng)配置文件的代碼實(shí)例,使用到了ConfigurationManager類,需要的朋友可以參考下2015-12-12
NumberToUpper數(shù)字轉(zhuǎn)中文詳解
本文介紹NumberToUpper數(shù)字轉(zhuǎn)中文的方法,大家參考使用吧2013-12-12
C#實(shí)現(xiàn)統(tǒng)計(jì)字?jǐn)?shù)功能的方法
這篇文章主要介紹了C#實(shí)現(xiàn)統(tǒng)計(jì)字?jǐn)?shù)功能的方法,較為詳細(xì)的分析了C#字?jǐn)?shù)統(tǒng)計(jì)功能的原理與實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08
C# 實(shí)現(xiàn)SDL2進(jìn)行視頻播放窗口截圖和字幕添加
這篇文章主要介紹了C# 實(shí)現(xiàn)SDL2進(jìn)行視頻播放窗口截圖和字幕添加,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12

