0

I'm trying to learn more programming as I progress through and started learning about vectors. What I just programmed here is that, I want the vector array to display random values at the given element input. So if I say I input 6 elements, each element would show random values. But, my program only outputs one random value.

int main(){

    vector<int>sam;
    cout << "How many elements?";
    int num;
    cin >> num;

    srand(time(0));
    for (int i = 0; i < num; i++){
        sam.push_back(num);
        sam[i]=rand()%100;
    }
    cout << "The vector array is: " << endl;
    for (int i = 0; i <num; i++){
        cout << sam[i] << endl;
        system("pause");
    }

}

How do I make the program show different random values of the given input? Any tip/help is really appreciated :)!

  • 1
    Lookup C++ random number generators. – David G Aug 17 '14 at 18:24
  • 1
    [Works for me](http://ideone.com/gzcRjy) – Igor Tandetnik Aug 17 '14 at 18:58
  • 1
    I'm with @0x499602D2, since you are learning, learn the proper way since the beginning and throw away the C random features. Look at [``](http://en.cppreference.com/w/cpp/numeric/random) – Manu343726 Aug 17 '14 at 19:13
  • It works for me ,osx 10.9.4 gcc version: prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.3.0 Thread model: posix – frank.lin Aug 18 '14 at 06:45
  • 1
    I don't suppose you just tried: `sam.push_back(rand()%100)` in your loop rather than the needless use of *both* `push_back` and `operator[]` ? And seriously, use [**``**](http://en.cppreference.com/w/cpp/numeric/random) instead. Once you do, you'll *never* go back to the C-runtime prng junk. It deals with many issues such as [*modulo bias*](http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator) that your current method suffers from (not that big a deal for such a small range, but still...). – WhozCraig Aug 18 '14 at 07:37
  • @Manu343726 I see, I'll look into :) thanks so much for your help! and for those it worked, ,_, what went wrong for me? I'll see and fix this after taking advises here. Thanks so much everyone! – user3838106 Aug 18 '14 at 16:04

0 Answers0