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ā)的個數(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è)計之線程使用技巧總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#數(shù)組操作技巧總結(jié)》及《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》
希望本文所述對大家C#程序設(shè)計有所幫助。
相關(guān)文章
C#實(shí)現(xiàn)將批量圖片轉(zhuǎn)為PDF文件
這篇文章主要為大家詳細(xì)介紹了如何使用 iTextSharp 庫實(shí)現(xiàn),將指定目錄下的有序的一組圖片,組合生成指定文件名的PDF文件,有需要的可以了解下2024-10-10
C#日期格式字符串的相互轉(zhuǎn)換操作實(shí)例分析
這篇文章主要介紹了C#日期格式字符串的相互轉(zhuǎn)換操作,結(jié)合實(shí)例形式分析了C#日期格式字符串的相互轉(zhuǎn)換操作函數(shù)與相關(guān)使用技巧,需要的朋友可以參考下2019-08-08

