is there a better way for this random 500-1000?

is this the way you would generate a number from 500 to 1000, or this there a more efficient way, cuz when i run this it sometimes takes awhile to come up with a number(meaning the do-while loop and if-else)??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int generate_random(int ran);

int main(int random)
{
    int your_number = generate_random(random);
    cout << "Your ID number is "<< your_number <<endl;
}

int generate_random(int i)
{
    do
    {
        srand(time(0));
        i = (rand() % 1000) + 1;
        if(i < 500)
            continue;
        else
            return i;
    }while(i < 500);
}
Last edited on
closed account (3hM2Nwbp)
1
2
3
4
5
// Sneaky Trick
int generate_random()
{
    return (rand() % 500) + 500;
}


:)

Ah and I should mention that srand only needs to be called once during the life of your program.
Last edited on
thanks
one question though, how come using the same technique
(rand() % 1) + 12;
always returns the number 12
wouldnt it return from 1 to 12???
Any number modulo 1 is 0, and 0 + 12 == 12.
Topic archived. No new replies allowed.