is this code correct?

im trying to make random numbers and i was wondering if this code is right.

include
1
2
#include <ctime>
#include <cstdlib> 


1
2
3
srand((unsigned)time(0));
int Random; 
Random = (rand()%4+1); //generate number 1-4  
correct
yep, just don't use multiples of srand throughout your code. and that means in no loops. Typically putting up with your variable declarations is best place.
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
26
27
28
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int getRandNum(int);

int main()
{
    srand(time(NULL));
    int number;

    for ( int i=0; i<10; i++ )
    {
        number = getRandNum(50); // get a number from 1-50
        cout << number << "\n";
    }

    cout << endl;
    return 0;
}

int getRandNum(int numbOutOf)
{
    return (rand() % numbOutOf + 1);
}
Last edited on
Returns a number in range [min,max). (min inclusive, max exclusive)
1
2
3
int random(int min, int max) {
    return std::rand()%(max-min)+min;
}
thanks for the tip gcampton, i never knew that. can i put line 3 on more than one line?
Last edited on
if you mean rand() yea, you can have as many as you want.. However a function like the one ROmai or I posted would be better as it's LESS upkeep long term.

But yea just keep the srand((unsigned)time(NULL)) in a simple selection of code. you can keep it in int main() if you have your rand() in another class, or perhaps just put it in the driver of that class.
Up to you, you can actually have multiples if you wish (there's no reason to), but just don't put them where your calling rand() from. for example this would be the WRONG way to go about this function:

1
2
3
4
5
int getRandNum(int min, int max)
{
    srand(time(NULL));
    return rand() % (max-min) + min;
}


Last edited on
Topic archived. No new replies allowed.