-1

I want to randomize variables a and b to output a random number 1 through 4 in the format of a,b. However, when I run my following code, the output is always the same no matter how many times I run it. For example, the output is always: 4,3 (same output shown 10 times.)

What did I do wrong here? Can someone point me in the right direction? Thanks!

#include <iostream>

using namespace std;

int main() 
{
    int x;
    int a, b;
    a= rand() % 4 + 1; 
    b= rand() % 4 + 1;
    x = 0;

    while (x < 10) {
    x++;

    cout << a << "," << b << endl;

    }
    return 0;
}
Anna Nguyen
  • 33
  • 1
  • 11
  • 3
    Does this answer your question? [Why do I always get the same sequence of random numbers with rand()?](https://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same-sequence-of-random-numbers-with-rand) – SPM Feb 01 '20 at 21:03
  • 5
    You need to set `a` and `b` _inside_ the loop otherwise they only get set once before the loop and never change. – 001 Feb 01 '20 at 21:04
  • Because it's not seeded, as well, http://c-faq.com/lib/srand.html. – Neil Feb 01 '20 at 21:10
  • I see what I did wrong now. Thanks! – Anna Nguyen Feb 01 '20 at 21:12
  • @JohnnyMopp: Are you sure? I wonder why voting up on incorrect comment! – Raindrop7 Feb 01 '20 at 21:23
  • 1
    Some entertaining and educational viewing on generating random numbers in the modern day: [rand() Considered Harmful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – user4581301 Feb 01 '20 at 21:39

2 Answers2

0

What did I do wrong here? Can someone point me in the right direction? Thanks!

You are setting a and b once and therefore they have the same value. To fix this, set them inside the loop to give them a new value each iteration:

while (x < 10) {
    x++;
    a = rand() % 4 + 1;
    b = rand() % 4 + 1;

    cout << a << "," << b << endl;
}

If you don't want the same values each time, you can call

srand(time(0)); // before the loop
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
0

You need to set the time seed first then call rand() otherwise you'll get always the same values:

int a, b;        //store random number
std::srand(std::time(0)); // set the time seed   

for(int i = 0; i != 10; ++i)
{
    a = rand() % 4 + 1;
    b = rand() % 4 + 1;
    cout << a << "\t" << b << endl;
}
  • Don't forget to include <ctime> header.
Maestro
  • 2,512
  • 9
  • 24