-1
函數應該從用戶傳遞的範圍中寫入數組不可重複的隨機數。我試過發現錯誤,並且我意識到它必須是第二個循環的東西(計數器j
),我知道它是無限循環,但我不知道爲什麼。我知道這是一個簡單的練習,但我真的不知道。謝謝你們的幫助。函數將範圍內的隨機數保存到數組而不重複
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int n, from, to, range, random, term;
int arr[100];
cout << "Count of numbers" << endl;
cin >> n; cout << endl;
cout << "Down range" << endl;
cin >> from; cout << endl;
cout << "Up range" << endl;
cin >> to; cout << endl;
range = to - from;
for (int i = 0; i < n; i++) {
random = (rand() % range) + from;
term = 1;
//Check if repeat
for (int j = 0; j < i; j++) {
if (arr[j] == random) {
term = 0;
}
}
//Write in to the array
if (term == 1) {
arr[i] = random;
}
else {
i = i - 1;
}
}
for (int f = 0; f < n; f++) {
cout << arr[f] << endl;
}
return 0;
}
「我試圖找到錯誤」是非常,非常從一個「明確的問題陳述」爲止。 –
生成少量非重複隨機數的一種簡單方法是用數字序列填充數組,然後使用隨機數對來交換數組元素多次。 –
解決這個問題的另一種方法是生成所有數字,然後使用Fisher-Yates對數字進行洗牌http://stackoverflow.com/questions/22850316/how-to-shuffle-elements-in-a-vector-randomly –