2011-01-29 61 views
0

我正在構建一個程序,其中用戶鍵入一個數字(n)並創建一組隨機數。例如,如果用戶輸入8,則應該創建八個隨機數,它們的範圍應該在0-999,999之間。該程序似乎正在編譯,唯一的問題是,只有一個隨機數正在生成。在C++中使用矢量創建隨機數

#include <iostream> 
#include <vector> 
#include <cstdlib> 

using namespace std; 

main() 
{ 
    int n; 
    int r; 
    int i; 
    int j; 
    vector<int> v; 

    cout << "Enter size of vector: "; 
    cin >> n; 

    for (i = 0; i < n; i++) 
    { 
     v.push_back(n); 
     r = rand() % 1000000; 
     v[i] = r; 
    } 

    cout << r << endl; 

誰能告訴我什麼,我做錯了,並會產生什麼,我需要一個以上的隨機數呢?

+0

你怎麼知道只有一個數字正在生成?最後您的cout聲明只會打印一個號碼。 – GWW 2011-01-29 01:13:54

+0

不要忘記調用`srand(time(0))` – 2011-01-29 01:32:47

回答

4

出了什麼問題明顯:

for (int i=0; i<n; i++) 
    v.push_back(rand()%1000000); 

它看起來像你產生隨機數的正確的數量,但是當你做,你打印r代替v,這是什麼包含隨機數字。

編輯:std::vector不支持operator<<直接,所以你可以使用一個循環打印出來的內容:

for (int i=0; i<v.size(); i++) 
    std::cout << v[i] << '\n'; 

,或者您可以使用std::copy

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n")); 

有,的當然,各種其他的可能性,以及...

編輯2:這是什麼克里斯·魯茨建議我一個完整的/正確的版本ñ他的評論:

#include <vector> 
#include <iostream> 
#include <algorithm> 
#include <iterator> 
#include "infix_iterator.h" 

template <typename T> 
std::ostream& operator<<(std::ostream &o, const std::vector<T>& v) { 
    o << "["; 
    std::copy(v.begin(), v.end(), infix_ostream_iterator<T>(o, ", ")); 
    o << "]"; 
    return o; 
} 

#ifdef TEST 
int main() { 

    std::vector<int> x; 

    for (int i=0; i<20; i+=2) 
     x.push_back(i); 

    std::cout << x << "\n"; 
    return 0; 
} 
#endif 

雖然這不是絕對必要的,它使用一個ostream_infix_iterator我張貼前一段時間。

2

它看起來像你的程序只打印出一個值:

cout << r << endl; 

即使它看起來像給定的循環正確產生隨機數的權數。你確定你沒有創建正確的數字嗎?

3

使用srand(time(0))播種,這樣你就真的得到了僞隨機數

0

移動cout << r << endl;你的循環中,那麼它會顯示RAND碼,並繼續在其循環。