我創建了一個包含36個1-49之間的亂數字的陣列。我在for回圈中嵌套了一個do-while回圈,將數字插入陣列中,以洗掉任何重復的數字。當運行代碼進行測驗時,我得到一個例外 "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"
{
隨機rand = new Random()。
int[] Numbers = new int[36] 。
for (int r = 0; r <= 36; r )
{
int nextValue;
do
{
nextValue = rand.Next(1, 50) 。
} while (Numbers.Contains(nextValue));
Numbers[r] = nextValue。
}
return Numbers。
}
Numbers[r] = nextValue;引起了例外。
有誰知道我在哪里出了問題嗎?
uj5u.com熱心網友回復:
你用36個空格來初始化你的數字陣列
Numbers = new int[36] 。
但是在你的回圈里面,你分配給數字的位置是49
for (int r =0; r <=49; r )
.....
Numbers[r] = nextValue。
你的回圈最大值應該改為36,它與你要求的隨機生成的最大值無關
。轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/327344.html
標籤:
