how to use rand() function with a range in C [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C, how do I get a specific range of numbers from rand()?
Generate a random number within range?
I'm stuck on how to use the rand() function and include a range for that random number. I need a random number between 67.00 and 99.99 only to be printed.
This is what I have tried, but failed with...
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x = rand();
if(x>=67.00)
if(x<=99.99)
printf("%d\n",x);
else
printf("not in range");
}

Instead of checking if the result is in the range, you can force the result to be in the range that you want:
int HIGH = 100;
int LOW = 67;
int rnd = LOW + (rand() % (HIGH-LOW));
The value of rnd is in the range between LOW and HIGH-1, inclusive.
If you do not want to force the number into range, change your condition to
if(x>=67.00 && x<=99.99)
Currently, the else belongs to the inner if, so the second printf does not happen when the number is less than 67.

Related

Why does my srand(time(NULL)) function generate the same number every time in c? [duplicate]

This question already has answers here:
Random numbers in C
(10 answers)
How can I generate different random numbers for each player?
(3 answers)
Closed 4 years ago.
So I was creating a program that would call a function and return 0 or 1 (0 meaning tails and 1 meaning heads) and then use that to print the outcome of 100 flips.
It seemed simple enough thinking I could use srand(time(NULL)) to seed rand() with constantly varying seeds. Here was my first crack.
#include <stdio.h>
#include <stdlib.h>
int flip();
int main(void) {
int heads = 0;
int tails = 0;
for (short int count = 1; count <= 100; ++count) {
int number = flip();
if (number == 0) {
printf("%s", "Tails");
++tails;
}
else if (number == 1) {
printf_s("%s", "Heads");
++heads;
}
}//end for
printf_s("\n%d Tails\n", tails);
printf_s("%d Heads", heads);
}//end main
int flip(void) {
srand(time(NULL));
int number = (int)rand();
printf("%d", number%2);
return number%2;
}//end flip
I would run the program and my rand() value would always be a five digit integer repeated in each iteration of the for statement (i.e 15367, 15745, or 15943).
I messed around until I discovered changing srand(time(NULL)) to srand(time(NULL)*time(NULL)/rand()) did the trick.
My only thought is that the time between each for iteration is so small the the time(NULL) part of the srand() function doesn't change enough to feed a different seed value.
I also tried srand(time(NULL)/rand()), however, this produced the same result (52 heads 48 tails) every time I ran the program (20+times); however, the rand() values were all different from each other.
I do not know why these things happened, or why the final srand(time(NULL)*time(NULL)/rand()) function worked, and I would love it if someone could explain!
The reason is, that time(NULL) changes only once per second!
This means, that you seed the random number generator 100 times with the same seed.
A better way is to seed the RNG only once at start of the process (at the head of main(), then you should get different values.
If you start your program more often than once a second, you could also seed it with
srand(time(NULL)+getpid());
or similar.

Generate random number in range [min,max] [duplicate]

This question already has answers here:
How to generate a random integer number from within a range
(11 answers)
Closed 7 years ago.
I am using C to generate a integer random number in range [min max]. I am using
int random_int(int min, int max)
{
return min + rand() % (max - min);
}
But I think above code is for range : [min, max), it is not for [min max]. Could you show to me a code to do my work. Best thanks
As you guessed, the code does indeed generate random numbers which do not include the max value. If you need to have the max value included in the range of random numbers generated, then the range becomes [min,max+1). So you could simply modify your code to:
int random_int(int min, int max)
{
return min + rand() % (max+1 - min);
}
P.S.: that is provided the quality of the original 'modulo' pseudo-random number generator you posted was not a concern (see this post for some more details with respect to what #undefinedbehaviour was referring to in comments).

Generating unique random numbers except from a specific one in C [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 9 years ago.
I was wondering, how can I generate unique random numbers except from a specific one. For example, if I want to generate numbers in range 1 to 10 except from 3, the output should be something like this:
7 6 1 2 4 9 5 8 10
Shuffle the numbers 1 - 10 and remove 3.
It doesn't matter if you remove the 3 before or after shuffling.
Alternatively, shuffle the numbers 1 - 9 and relabel 3 as 10...
For shuffling without bias you can use for example the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Generate random number in the range 1..9 and add one if the number is greater than or equal to 3.
Generate a number. Check its value, if the number is 3 generate another one. If it isn't 3 then use it.
EDIT: Thinking before coffee is a terrible plan. If you want to get every number in the range in a random order then I agree with the others talking about shuffling lists. If however you want some random subset of the range I would store a list of forbidden values. Shuffling and only taking the first n numbers would also be suitable if the range isn't very large (e.g. not something like 0<x<INT_MAX).
Every time you generate a number check if the generated number is on the forbidden list and if it is, generate another number. Every time you generate a valid number you add it to the list to ensure generated numbers are unique. The list should also be initialised with your unwanted numbers (3 in the example given).
You may try like this:-
unsigned int
randomnumber(unsigned int min, unsigned int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
then later you can do this:-
x = randomnumber(1,10);
if (x==3)
{ x = x+1;}
or
if (x!=3)
{ printf("%d",x)}
This is my answer - returns random value in [min, max), except "except".
int myrand(int min, int max, int except) {
int rc;
do {
rc = min + rand() % (max - min);
} while(rc == except);
return rc;
}
This code will generate unique random numbers from minimum to maximum of a given range.
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, min_range, i = 0, rand_num;
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
printf("Enter your minimum of range: ");
scanf("%d", &min_range);
bool digit_seen[max_range + 1]; // VLAs For C99 only
for (int i = min_range; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + min_range;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}

Generate a Random Number between 1 and N-1 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate a random number from within a range - C
How would you generate a random number between 1 and N-1 where N is a number the user punches in?
So far, my code is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number = 0; //number variable
printf("This program will ask you for a number, an integer, and will print out a random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user.
//gets the input
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &number); //gets the input and stores it into variable number
return (0);
}
Try something like this:-
unsigned int
randomr(unsigned int min, unsigned int max)
{
double x= (double)rand()/RAND_MAX;
return (max - min +1)*x+ min;
}
Check out this link:- http://c-faq.com/lib/randrange.html
Here is the link to the referece for random.
http://www.cplusplus.com/reference/cstdlib/rand/
you can use
num= rand() % n + 1;
Depending on how "random" you want your numbers to be, you can use rand() function from the standard libc. This function will generate numbers between 0 and RAND_MAX. You can then get the result in the good range by using a modulo operation.
Note that this generator (a LCG) is neither suitable for cryptographic applications nor scientific applications.
If you want more suitable generators, have a look at generators such as Mersenne Twister (still not cryptosecure though).
You need to look at rand. Bit of maths and you have a solution.

How to assign a variable to rand() In C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate a random number within range?
I am trying to make it so when the code is executed, I can type the max number in
command prompt to redefine the max number and generate a new random number inbetween 0 and new Max number.
Did I do this correctly?
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
int randomnumber ;
int max;
srand( time(NULL) );
scanf("Enter total number of students %d",&max);
randomnumber=rand()% 30;
printf("This is your random number\n %d",randomnumber);
getchar();
return 0;
}
You've used the scanf to send a message to the user, but you need to use printf for that. Try:
printf("%s", "Enter total number of students: ");
scanf("%d",&max);
You can then change the %30 to %max to give the user a number between 0 and max - 1.
randomnumber=rand()% max;
As commenters have said, using modulo to reduce the range of rand() will not give you a good random distribution. Also, be sure to check that max is greater than 0, otherwise you will get an error.
If you're wondering why you're getting a large number in max at the moment, it is because you're not initializing max explicitly. With C and C++ this means that there can be junk data in there. It is not like Java or C# where an int is automatically initialized to 0.

Resources