2

I'm only seeding rand() once, yet I have a sort of odd problem... When I do,

int r = rand() % 7 + 1;

it returns 4 every time.

But if I replace that 7 with any other number, it works just fine.

Any idea why this is happening?

My full code's all cluttered right now, but here's basically what's giving me the problem:

int main() 
{
    srand(time(0));
    int r = rand() % 7 + 1;
    cout << r;
}

Even when I run it just like this, with nothing else, it still only returns 4.

P/S: For a little context, I'm working on a super simple amazons solitaire game that runs in the console (yes, I'm aware that console games aren't ideal. I just needed a simple amazons solitaire game I can play on my computer for whenever I don't have a deck of cards around.) which is why the random number has to be between 1 and 7.

PP/S: I'm using Xcode.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    I'm not able to reproduce the problem with the code you've shown. (Also, unrelated, but I can't help but [think of this](https://xkcd.com/221) ...) – Rufflewind Feb 10 '15 at 20:31
  • 3
    @Rufflewind: I have the vaguest memory that there's a compiler (version?) that had a quirk that `rand()%7==4` very very often. I think it was a specific version of xcode. I'll try to remember... – Mooing Duck Feb 10 '15 at 20:33
  • well, you ARE seeding this with what is essentially a constant. try doing a couple rounds of `rand()` and `cout` in the same program and see if you get different values WITHIN that same instance of the program. – Marc B Feb 10 '15 at 20:34
  • 3
    I'd just found [why does rand()%7 always return 0?](http://stackoverflow.com/q/7866754/845092) – Mooing Duck Feb 10 '15 at 20:39
  • 1
    Haha, good ol' xkcd... As for running it a couple times within the program, I was getting 2 a lot, then I was getting 1 for the second output, every time I re ran the program. – katamaridamacy Feb 10 '15 at 20:47

0 Answers0