What's new

C programming - Random number between two numbers

warfareknow

BANNED
Joined
Apr 4, 2015
Messages
463
Reaction score
-6
Country
Iran, Islamic Republic Of
Location
Israel
Hi, so if I want a random number between 0 and x in C
I can use this:

Code:
srand(time(NULL))
int random = rand() % x +1;

But how does this work between a range like 2 - 12?
 
Code:
    int i;
    srand(time(NULL));
    for (i = 0; i < 1; i++)
    printf("%i\n", (rand() %10 ) +2);
    return 0;

Does this work for 2 -12 ?
 
Last edited:
Hi, so if I want a random number between 0 and x in C
I can use this:

Code:
srand(time(NULL))
int random = rand() % x +1;

But how does this work between a range like 2 - 12?

What about geting random number between 0 and 10 and adding 2 ?
 
Hi, so if I want a random number between 0 and x in C
I can use this:

Code:
srand(time(NULL))
int random = rand() % x +1;

But how does this work between a range like 2 - 12?

The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand. Since a digital machine is always deterministic.

rand() % x; means generated random number is divided by x and gives remainder as result. Remainder will be between 0 and x...

then you add 1 to it... so you get a number 1 and x+1

int i;
srand(time(NULL));
for (i = 0; i < 1; i++)
printf("%i\n", (rand() %10 ) +2);
return 0;

this gives randn between 2 and 12
 
Think about it for a second and you should be able to figure it out.

You have a formula that makes a random number between 0 and N.

You want a formula to translate that to a number between A and B.

How might you move the range around a little bit?

If I gave you a formula that made results 0-5, and you wanted the results to be between 2 and 7, how would you do that?

Anyway

int x =(rand() % 10)+10; numbers from 10 - 20

Easiest way to solve.

@f1000n maybe you can help here (add more) since programming is just my hobby and my field (chemical engineering) is a bit different.
 
Last edited:
Think about it for a second and you should be able to figure it out.

You have a formula that makes a random number between 0 and N.

You want a formula to translate that to a number between A and B.

How might you move the range around a little bit?

If I gave you a formula that made results 0-5, and you wanted the results to be between 2 and 7, how would you do that?

Anyway

int x =(rand() % 10)+10; numbers from 10 - 20

Easiest way to solve.


I came to the solution in post 2 but thanks anyway.

My problem was i did forget the () so i had weird outputs that was also the reason i asked it here but i went through the code and put those parantheses and had the range i needed.

______________________________________________
Again thanks for your help @Lotus_stalk @Saif al-Arab :*
 
Back
Top Bottom