using System;
using System.Linq;
namespace Loto
{
class Program
{
static void Main(string[] args)
{
short[] tirage = new short[6]; //array that contains the numbers
short nbTirage; //the number randomed
for (int i = 0; i < 6; i++)
{
nbTirage = NombreAleatoire();
while (tirage.Contains(nbTirage)) //if the number has already been drawn
{
nbTirage = NombreAleatoire(); //we random another one
}
Console.Write(nbTirage + " "); //writing the result
}
}
static short NombreAleatoire()
{
Random nb = new Random();
return (short)nb.Next(1, 49);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是完整的计划.
它应该包括1到49之间的7个唯一数字.该程序在调试模式下运行良好,但是当我从exe运行它时,它绘制相同数字的7倍.是什么造成的?我正在使用Visual Studio.
Random快速连续创建一个新对象会为该对象的每个实例提供相同的(基于时间的)种子,因此它们将生成相同的数字.
使用单个实例Random生成正在进行的数字.像这样的东西:
Random nb = new Random();
for (int i = 0; i < 6; i++)
{
nbTirage = (short)nb.Next(1, 49);
while (tirage.Contains(nbTirage)) //if the number has already been drawn
{
nbTirage = (short)nb.Next(1, 49); //we random another one
}
Console.Write(nbTirage + " "); //writing the result
}
Run Code Online (Sandbox Code Playgroud)
(注:不经历在调试模式下此相同的行为,如果你不暂停执行该代码的种子,Random是基于当前的时间,因此靠暂停你让时候通过代码的执行,从而改变了.删除所有断点并让应用程序在调试模式下完全执行,您将看到在发布模式下看到的相同行为.)
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |