我已經放在一起在objective-c中的一些代碼,以幫助我爲彩票選擇器程序創建一個隨機數字發生器。但我似乎有一個問題,即使在有聲明要先檢查它的時候,它有時也會在5個不同的列中出現相同的數字。 當它編譯並運行時,它會創建隨機數和大部分時間它們是不同的,但它會在不同的時間在兩行中出現相同的數字時,它不應該。Objective-C隨機數發生器爲抽獎選擇器錯誤
我已經嘗試了雄both蘭特()和arc4random(),都給我同樣的問題。
int rNumber1 = arc4random() % 55 + 1; // 55 because it chooses from 0 to 55 then we add one, max 56
int rNumber2 = arc4random() % 55 + 1; // 55 because it chooses from 0 to 55 then we add one, max 56
int rNumber3 = arc4random() % 55 + 1; // 55 because it chooses from 0 to 55 then we add one, max 56
int rNumber4 = arc4random() % 55 + 1; // 55 because it chooses from 0 to 55 then we add one, max 56
int rNumber5 = arc4random() % 55 + 1; // 55 because it chooses from 0 to 55 then we add one, max 56
// First number box result
textView01.text = [[NSString alloc] initWithFormat:@"%d", rNumber1];
// Second number box result not equal to first box number
if (rNumber2 != rNumber1) {
textView02.text = [[NSString alloc] initWithFormat:@"%d", rNumber2];
} ;
// Third number box result not equal to first or second box number
if (rNumber3 != rNumber1 || rNumber2){
textView03.text = [[NSString alloc] initWithFormat:@"%d", rNumber3];
} ;
// Fourth box number result not equal to first, second or third number box number
if(rNumber4 != rNumber1 || rNumber2 || rNumber3){
textView04.text = [[NSString alloc] initWithFormat:@"%d", rNumber4];
} ;
// Fifth box number result not equal to first, second, third or fourth number box number
if (rNumber5 != rNumber1 || rNumber2 || rNumber3 || rNumber4){
textView05.text = [[NSString alloc] initWithFormat:@"%d", rNumber5];
} ;
// Sixth box number independant of other boxes, up to 46 max number
int rNumber6 = rand() % 45 + 1; // 45 because it chooses from 0 to 45 then we add one, max 46
textView06.text = [[NSString alloc] initWithFormat:@"%d", rNumber6];
+1集合是一個更加「客觀」的解決方案,並且可以輕鬆地推廣到挑選任意數量的項目。 –
感謝您提供此代碼和信息,它似乎更好。我使用了+1,因爲我想確保我沒有得到一個零,因爲它從零開始選擇數字。那麼爲什麼它不給我一個56? – Mirko
'%55'是除以55後的餘數。這個數值從0到54不等。當你給這個範圍加1時,範圍從1到55不等。 –