我對編程相當陌生(幾天前開始),我決定製作一個隨機數生成器。我的問題是,我無法生成一個非常大的數字。我搜索了四周,並且讀到可以將'int'更改爲'long',但是當涉及到隨機數生成器時,我遇到了麻煩。C#無法從'long'轉換爲'int'(隨機數生成器)
這裏是我的代碼部分:
long min;
long max;
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("Minimum Number: ");
min = Convert.ToInt64(Console.ReadLine());
Console.Write("Maxinum Number: ");
max = Convert.ToInt64(Console.ReadLine());
if (max < min)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("You must choose a larger number! Press any key to restart...\n");
Console.ReadKey(true);
Generator();
}
Random randomnumber = new Random();
while (true)
{
long randomnumout = randomnumber.Next(min, max + 1);
Console.ForegroundColor = ConsoleColor.White;
int randomsleep = randomnumber.Next(250, 750);
Console.WriteLine("\nGenerating...");
Thread.Sleep(randomsleep);
}
在Visual Studio中,
randomnumber.Next(min, max + 1)
有下劃線
的錯誤:
Error 2 Argument 1: cannot convert from 'long' to 'int'
Error 3 Argument 2: cannot convert from 'long' to 'int'
Error 1 The best overloaded method match for 'System.Random.Next(int, int)' has some invalid arguments
我周圍中搜索在線,而我仍然感到困惑編輯。
將您的長變量更改爲int – DavidG 2015-02-07 10:02:44
Random.Next()需要整數,您試圖給它多頭。如果您需要的數字大於您可以使用整數獲得的數字,請參閱http://stackoverflow.com/a/6651661/279516。 – 2015-02-07 10:03:28
@DavidG:這並不能解決Alvin試圖「產生極大數量」的問題; Alvin需要的是一個Random.Next,它返回一個長(在BCL(AFAIK)中沒有)。所以他必須找到另一種方式;說:生成兩個int32的和移動一個左邊的32位,並將它們加在一起,如鮑勃霍恩建議(見他的鏈接)。 – RobIII 2015-02-07 10:08:53