2017-03-27 56 views
-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; 
} 
+5

「我試圖找到錯誤」是非常,非常從一個「明確的問題陳述」爲止。 –

+0

生成少量非重複隨機數的一種簡單方法是用數字序列填充數組,然後使用隨機數對來交換數組元素多次。 –

+0

解決這個問題的另一種方法是生成所有數字,然後使用Fisher-Yates對數字進行洗牌http://stackoverflow.com/questions/22850316/how-to-shuffle-elements-in-a-vector-randomly –

回答

0

如果你想不重複的在一定範圍內的隨機數,你能做到這一點,像這樣:

#include <random> 
#include <iostream> 
#include <set> 

int main() 
{ 
    int n, from, to; //, range, random, term; // The last three are not used 

    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; 

    std::random_device rd; // Random seed 
    std::mt19937 gen(rd()); // Create a random number geenrator, and seed it 
    std::uniform_int_distribution<> dis(from, to); // Define the range 

    std::vector<int> ints(1, dis(gen)); 

    while (ints.size() < n) 
    { 
     int t = dis(gen); 
     if (t != ints.back()) 
      ints.push_back(t); 
    } 
} 

UPDATE

對不起,我想讀您的文章。這是我的原始答案。如果你想在一定範圍內獨特隨機數,你能做到這一點,像這樣:

#include <random> 
#include <iostream> 
#include <set> 

int main() 
{ 
    int n, from, to; //, range, random, term; // The last three are not used 

    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; 

    std::random_device rd; // Random seed 
    std::mt19937 gen(rd()); // Create a random number geenrator, and seed it 
    std::uniform_int_distribution<> dis(from, to); // Define the range 

    std::set<int> ints; 

    while (ints.size() < n) 
    { 
     ints.insert(dis(gen)); 
    } 
}