cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
General C++ Programming
Need help with generating random numbers
Need help with generating random numbers
Oct 11, 2012 at 1:17am UTC
sabi20
(22)
I need to generate random numbers between 100 and 999
this is what i got but this doesn't work every time. It goes over 999 sometimes
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num;
int count = 1;
unsigned seed = time(0);
srand(seed);
while(count <= 20)
{
num = 100 + rand() % 999;
cout << num << endl;
count++;
}
}
Oct 11, 2012 at 1:25am UTC
scorlibrian
(3)
The modulus operator is resolved before addition in the order of operations. You're essentially generating a number between 0 and 999 and then adding 100, making your limits between 100 and 1099.
Change the line to "num = 100 + rand() % 899;"
That should work.
Topic archived. No new replies allowed.