3

I just wrotte the code below in C++, but I have one problem: the random number that cames it's always the same..!! Here's my code and a screenshot:

#include <iostream>
using namespace std;

int main() {
    cout << "I got a number in my mind... can you guess it?" << endl;
    int random;
    random = rand() % 20 + 1;

    cout << random << endl;
    system("pause");
    return 0;
}

screenshot : http://tinyurl.com/n49hn3j

Radwan
  • 33
  • 1
  • 6

3 Answers3

12

srand(time(0)) will only produce a new random number if you do not start it in the same second you did the last time. Also there are issues with using rand() % 20. This will do the right thing:

#include <iostream> 
#include <random> 
int main(){ 
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(1, 20);
    std::cout << dist(mt);
}
nwp
  • 9,623
  • 5
  • 38
  • 68
  • 2
    importing the whole `std` `namespace` isn't always a good idea if you're only using a small part of it. just my $0.02 – Iosif Murariu May 10 '14 at 11:45
  • @IosifM. True. I though I can get away with it because its just inside a function and a code example, but of course it should be done right. I fixed it. – nwp May 10 '14 at 11:49
  • +1 for using the c++11 version and not propagating the mess that is rand() – dutt May 10 '14 at 11:50
  • @nwp: didn't mean to be a code nazi, just wanted to throw that out so that the OP would have this in mind. anyway, gj as dutt said – Iosif Murariu May 10 '14 at 11:52
0

you need to init (seed) the random using the srand function. more info

#include <iostream>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
using namespace std;

int main() {

    // Seed the random number generator
    srand(time(0));

    cout << "I got a number in my mind... can you guess it?" << endl;

    int random;
    random = rand() % 20 + 1;

    cout << random << endl;
    system("pause");
    return 0;
}
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
0

Try this instead:

#include <ctime>  //for current time 
#include <cstdlib> //for srand
    srand (unsigned(time(0))); //use this seed

This will also work for your random.

Nassim
  • 301
  • 3
  • 11