C#的随机函数怎样?

solarsoft 2001-10-10 10:11:43
C#的随机函数怎样?谢谢赐教.
...全文
57 4 打赏 收藏 举报
写回复
4 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
javanow 2001-10-10
namespace Lottery
{
using System;
using System.Collections;
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Lottery
{
public static int Numbers, EndRange;
//Displays titles and gets start values
public static void DisplayTitles()
{
EndRange=0;
Numbers=1;
while (EndRange<Numbers)
{

System.Console.WriteLine("=============================");
System.Console.WriteLine("Lottery number generator");
System.Console.WriteLine("=============================");
System.Console.Write("How many unique numbers? : ");
Numbers=Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter end range : ");
EndRange =Convert.ToInt32(System.Console.ReadLine());

}
}
//Generate our unique numbers and push them onto stack
public static void GenerateNumbers(Stack s, Dice d)
{
bool exists=true;
int i;
int val;

for (i=1;i<=Numbers;i++)
{
val=d.RollDice(EndRange); //Roll EM!
exists=s.Contains(val);
while (exists==true) //Reroll if we already
{ //have that number
val=d.RollDice(EndRange);
exists=s.Contains(val);
}
s.Push(val);
}
}

//Retrieve all values from the stack and output to console
public static void DisplayResults(Stack s)
{
for (int i=1;i<=Numbers;i++)
{
System.Console.WriteLine(s.Pop());
}
}

//Entry point for program
public static int Main (string[] args)
{
Stack s = new Stack();
Dice d = new Dice();
DisplayTitles();
GenerateNumbers(s,d);
DisplayResults(s);
return 0;
}
}

//Class to simulate a dice
public class Dice
{
public int RollDice(int sides)
{
Random r = new Random();
int i=0;
while(i==0)
{
i=r.Next(sides+1);//Get another random number but
} //discard zero values
return i;
}
}
}
  • 打赏
  • 举报
回复
javanow 2001-10-10
Random rnd = new Random(100);
int rndNum = rnd.Next(10); //得到的随机数

  • 打赏
  • 举报
回复
sam1111 2001-10-10
RandomNumberGenerator类
  • 打赏
  • 举报
回复
CForce 2001-10-10
Random rnd = new Random();
int rndNum = rnd.Next();int 取值范围内的随机数
int rndNum = rnd.Next(10);//得0~9的随机数
int rndNum = rnd.Next(10,20);//得10~19的随机数
int rndNum = rnd.NextDouble();//得0~1的随机数
  • 打赏
  • 举报
回复
发帖
C#

10.8w+

社区成员

.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
帖子事件
创建了帖子
2001-10-10 10:11
社区公告

让您成为最强悍的C#开发者