2016-05-12 40 views
0
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); 
     } 
    } 
} 

這是完整的程序。C#程序只能在跨越模式下正常工作

它應該畫出1到49之間包含7個唯一的數字。該程序在調試模式下運行良好,但是當我從exe中運行它時,它會繪製相同數字的7倍。是什麼原因造成的?我正在使用Visual Studio。

+1

你嘗試重建該程序? – Needham

+0

您需要保留一個Random對象,並在一個對象上調用Next .. +我沒有看到填充「tirage」+您可能爲了簡潔而刪除名稱空間和類。 –

+0

祝您嘗試製作LOTTO程序win ..否則,我們都會在一段時間之前變得富有。再加上使用調試器來遍歷你的代碼並檢查你正在創建的對象,你會立即看到缺陷發生的地方。 – MethodMan

回答

5

創建快速連續一個新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 
} 

(注意:您的經驗,這相同的行爲在調試模式下,如果不暫停執行該代碼爲Random種子是基於當前時間。因此,通過暫停代碼的執行,您可以讓時間通過,從而更改種子。刪除所有斷點並讓應用程序在調試模式下完全執行,您將看到與在發佈模式下相同的行爲。)

+0

哦,我不知道。所以我只需要把它從方法中拿出來。簡單。謝謝 – Lawliet

2

這是因爲Random的默認種子是您每播種一次的播種時間。您需要傳入Random對象以確保您獲得不同的號碼。

它正在調試步驟中工作,因爲迭代之間的時間慢得多,所以種子正在變化。

Random nb = new Random(); 

for (int i = 0; i < 6; i++) 
{ 
    nbTirage = NombreAleatoire(nb); 

    while (tirage.Contains(nbTirage)) //if the number has already been drawn 
    { 
     nbTirage = NombreAleatoire(nb); //we random another one 
    } 

    Console.Write(nbTirage + " "); //writing the result 
} 

static short NombreAleatoire(Random nb) 
{ 
    return (short)nb.Next(1, 49); 
} 
相關問題