This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 9 years ago.
So, I'm currently reading a book about C and, in an exercise, I should do a program that would get input from user (a number between 1 and 12) and would "roll" that number of dice, and then display the results.
The problem is, when it randomizes the dice numbers, all results are exactly the same. And I did use "srand((unsigned)time(NULL))" to seed. What could possibly be going wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int throw(void);
int main()
{
int many,x,sum;
sum = 0;
puts("R O L L ' E M !");
type:
printf("How many dice would you like to roll (1 - 12)? ");
scanf("%d",&many);
if(many>12) {
puts("You can roll up to 12 dice!");
goto type;}
if(many<1) {
puts("You need to roll at least one die!");
goto type;}
int num[many];
printf("\nRolling %d...\n",many);
puts("Here they come!");
printf(" ");
for(x=0;x<many;x++) /* Shows which die it is */
{
if(x>=9)
printf("%d ",x+1);
else
printf(" %d ",x+1);
}
putchar('\n');
for(x=0;x<many;x++) /* Thingy to illustrate the dice */
printf("+---");
puts("+");
for(x=0;x<many;x++) /* Shows dice results */
{
num[x] = throw();
printf("| %d ",num[x]);
sum = sum + num[x];
}
puts("|");
for(x=0;x<many;x++) /* Thingy to illustrate the dice */
printf("+---");
puts("+");
printf("Total = %d",sum); /* Shows total */
return(0);
}
int throw(void) /* "Throws" the dice, by randomizing a number between 1 and 6 */
{
int n;
srand((unsigned)time(NULL)); /* seed */
n = rand() % 6 + 1; /* randomizes and limits from 1 to 6 */
return(n);
}
You are calling srand before for each call to rand. srand initializes the algorithm with a seed. Probably because of the short time between the calls, the timestamp is the same, therefore the seed. As a result, you reinitialize the algorithm with the same value, therefore producing the same sequence of numbers. The solution is to call srand only once per thread.
you have to use srand() just one time at the beginning of your program, otherwise the rand() function uses the same seed for all the calls since srand is called many times in a very small time lapse, shorter than a second and the seed remains the same for all the calls..
Related
Hello i'm trying to create a program where it counts the number of heads and tails in a coin flip simulator based on the number of coin flips the user inputs. The issue with this is that when i'm trying to count the number of heads and tails then increment them, it gives me just a random number and not within the range of flips given.
This is a sample output of my error
Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 1804289393
Number of tails: 846930886
Instead I want it to count it like this:
Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 7
Number of tails: 3
Here's the program :
#include <stdio.h>
#include "getdouble.h"
#include <time.h>
#include <stdlib.h>
int main(void) {
printf("Coin Flip Simulator\n");
printf("How many times do you want to flip the coin? ");
int numFlip = getdouble();
if(numFlip == 0 || numFlip < 0) {
printf("Error: Please enter an integer greater than or equal to 1.\n");
}
int i = 0;
int numHead = rand();
int numTails = rand();
for (i = 0; i < numFlip; i++) {
if(numFlip%2 == 0) {
numHead++;
}
else {
numTails++;
}
}
printf("Number of heads: %d\n", numHead);
printf("Number of tails: %d\n", numTails);
return 0;
}
Thanks for the suggestions, it's my first time trying to use the random number generator.
I suggest you use an unsigned integer type for numFlip. The main issue is that you need to initialize numHead (sic) and numTails. You want to use srand() to seed the random number generate otherwise the result is deterministic. As you only have two options just record number of heads and determine the tails after the fact:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
printf("Coin Flip Simulator\n");
printf("How many times do you want to flip the coin? ");
unsigned numFlip;
if(scanf("%u", &numFlip) != 1) {
printf("numFlip failed\n");
return 1;
}
unsigned numHeads = 0;
for(unsigned i = 0; i < numFlip; i++)
numHeads += (rand() % 2); // removed ! when #Fe2O3 wasn't looking :-)
unsigned numTails = numFlip - numHeads;
printf("Number of heads: %u\n", numHeads);
printf("Number of tails: %u\n", numTails);
}
and example output:
Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 2
Number of tails: 8
I have made a while loop and it works partly. I want the code to stop when the values entered are under the parameter, but it keeps going regardless of the output. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
// defining variables until "till here" comment
int i;
int rollDice;
int firInp;
int secInp;
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(rollDice > 0)
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=1): "); // this message is printed after the users first input
scanf("%d", &secInp); // user input stored into secInp
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters
for(i = 0; i < secInp; i++){
rollDice = (rand()%firInp) + 1;
printf("%d \n", rollDice);
}
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
I'm new to C btw.
edit: I want the loop to continue if the user input is more than 24, 499 respectively.
What you're doing is wrong. Variable rollDice is for storing the values of the outcomes rather than doing a condition check. It will have random values and since the values on the dice can't be negative or zero it may not exit the while loop. I don't know what will rand() will produce so I'm just assuming.
The range for rand() is [0,RAND_MAX), including zero and excluding RAND_MAX. But because of this expression (rand()%firInp) + 1 , you're adding one to it. So it will never become Zero.
You can use a flag variable and set it to 1. When the if conditions are met, you can set the flag to 0. It will exit the while loop.
Corrected code :-
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
// defining variables until "till here" comment
int i;
int rollDice;
int firInp;
int secInp;
int flag = 1;
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(flag)
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=1): "); // this message is printed after the users first input
scanf("%d", &secInp); // user input stored into secInp
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters
for(i = 0; i < secInp; i++){
rollDice = ((rand() + 1)%firInp);
printf("%d \n", rollDice);
}
flag = 0;
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
EDIT :-
Also, division with 0 is undefined. rand() can attain value 0. You should add 1 to rand() rather than adding to whole modulus. It can create an error if the rand() will give 0 as an output.
I have started C recently and am having trouble make the computer think of a random number.
This is the code so far. I need help!
#include <stdio.h>
#include <stdlib.h>
int main ()
{
time_t t;
int userin;
printf("Guess a number from 1 to 10\n");
scanf("%d", userin);
int r = rand() % 11;
if (r == userin)
{
printf ("you are right");
}
else
{
printf("Try again");
}
return 0;
}
Thx a lot guys it worked out!!!!
In your code, r will be a random number from 0 to 10. For a random number between 1 and 10, do this:
int r = rand() % 10 + 1;
Also, you should call
srand(time(NULL));
at the beginning of main to seed the random number generator. If you don't seed the generator, it always generates the same sequence.
There is issue in your scanf statement as well.
You should use
scanf("%d", &userin);
instead of
scanf("%d", userin); /* wrong - you need to use &userin */
scanf needs the address of variables at which it will store the value. For a variable, this is given by the prefexing the variable with &, as in &userin.
There are few issues in your code.
not reading into the address & of your variable using scanf
not considering "legitimate" values of input, result of rand()%11 can also be 0
not checking against "illegal" input values, which can "alias" the result.
not properly initializing seed of the pseudo-random rand() function, so it always returns the same result.
Using printf for debugging your code, as in the following example, based on your code can help a lot:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DEBG 1
int main (void)
{
time_t t;
int userin;
printf("Guess a number from 1 to 10\n");
if(scanf("%d", &userin) != 1){ // read into the variable's address
printf("Conversion failure or EOF\n");
return 1;
}
if(userin < 1 || userin > 10){ // check against "illegal" input
printf("Offscale, try again\n");
return 1;
}
srand(time(NULL)); // initialize the seed value
int r = 1 + rand() % 10; // revise the formula
if (DEBG) printf("%d\t%d\t", r, userin); //debug print
if (r==userin){
printf ("you are right\n");
}else{
printf("Try again\n");
}
return 0;
}
Please, also consult this SO post.
Problems :
scanf("%d", userin); //you are sending variable
This is not right as you need to send address of the variable as argument to the scanf() not the variable
so instead change it to :
scanf("%d", &userin); //ypu need to send the address instead
and rand()%11 would produce any number from 0 to 10 but not from 1 to 10
as other answer suggests, use :
(rand()%10)+1 //to produce number from 1 to 10
Solution :
And also include time.h function to use srand(time(NULL));
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int userin;
printf("Guess a number from 1 to 10\n");
scanf("%d", &userin);
int r = (rand() % 10)+1;
if (r==userin)
{
printf ("you are right");
}
else
{
printf("Try again");
}
return 0;
}
Why use srand(time(NULL)) ?
rand() isn't random at all, it's just a function which produces a sequence of numbers which are superficially random and repeat themselves over a period.
The only thing you can change is the seed, which changes your start position in the sequence.
and, srand(time(NULL)) is used for this very reason
This should work
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int userIn = 0; //I like to initialize
printf("Guess a number from 1 to 10\n");
scanf("%d", &userIn);
srand(time(NULL)); //seed your randum number with # of seconds since the Linux Epoch
int r = (rand()%10)+1; //rand%11 gives values 0-10 not 1-10. rand%10 gives 0-9, +1 makes sure it's 1-10
if (r == userIn)
{
printf ("you are right\n");
}
else
{
printf("Try again\n");
}
return 0;
}
Edit: You may want to implement code to verify that the user input is in fact an integer.
Ok, so as a beginner programmer, I have been tasked with creating a simple math quiz program. It is supposed to prompt the user for how many questions to ask, congratulate or inform the user when their answer is either right or wrong. And then print out the number correct and the number incorrect at the end of the program. I have done all of this successfully, the only issue with my code now is that it asks the same questions over and over. I'm at a loss here so any help would be appreciated, thanks.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i;
int response;
int correctAnswers = 0;
int incorrectAnswers = 0;
printf("\nMath Quiz\n");
printf("Please enter # of problems you would wish to try:");
scanf("%d", &response);
if(response == 0)
{
printf("\nThanks for playing!\n");
return 0;
}
for(i=0; i<response; i++)
{
int answer = 0;
int a = rand() % 12;
int b = rand() % 12;
printf("\n%d * %d = ",a ,b);
scanf("%d", &answer);
if((a * b) == answer){
printf("\nCongratulations You are correct!\n");
correctAnswers++;
}
else{
printf("Sorry you were incorrect!\n");
incorrectAnswers++;
}
}
printf("\n\nYour Results:\n\n\n");
printf("Number Incorrect: %d\n", incorrectAnswers);
printf("Number Correct: %d\n", correctAnswers);
if(correctAnswers > incorrectAnswers){
printf("You Passed!\nGood work!\n\n");
}
else{
printf("You did not pass!\nYou need more work!\n\n");
}
return 0;
}
Additionally, any critiques as far as formatting are more than welcome. Thanks!
You need to understand how the randon number generator works in C.
rand() generates only pseudorandom numbers. This means that every time you run your code you will get exactly the same sequence of numbers.
Use the srand function to generate random numbers based upon a source number. If you want one that changes often, use the system time.
srand(time(NULL));
Also include the header file time.h to use the time function.
Call that function before any calls to rand(). If you don't call srand() before a call to rand() in your program, it is as if srand(1) was called: the seed value will be 1 at every execution of the program and the generated sequence will be always the same.
Use this srand in your code, like this...
int a;
int b;
srand(time(0));
a = rand() % 12;
b = rand() % 12;
This question already has answers here:
Generating random numbers in C
(7 answers)
Why does rand() always return the same value? [duplicate]
(2 answers)
Closed 9 years ago.
Programming in C, I am trying to run a game where the computer generates a number between 1 and 100. However, I keep getting 42 as the number generated... what is wrong with my "rand()"
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int guess, tries = 6;
int number = 1+(rand()%100);
printf("Pick a number between 1 and 100:");
scanf_s("%d", &guess);
while(tries > 0 && guess != number)
{
if(guess > number)
printf("Too high");
else
printf("Too low");
puts(". Guess again:");
scanf_s("%d",&guess);
tries--;
}
if(guess == number)
puts("You win!");
else
puts("You lose");
}
after a good amount of discussion below I added in the fallowing lines of code
#include <time.h>
and
srand ((unsigned int)time(NULL));
but the code failed to run in MS visual studio until i googled the error and it turns out that MSVS needs the variebles to be declared at the top of each function/block. after doing this the code works fine. Thank you everyone and sorry for the multiple edits. corrected code:
#include <time.h>
int main (void)
{
int guess, tries = 6, number;
srand ((unsigned int)time(NULL));
number = 1+(rand()%100);
The rest is the same. Thank you all.
Use a seed with time
To seeds the pseudo-random number generator used by rand() with the current time.
srand(time(NULL));
before calling rand
You need to initialize the random seed with
srand (time(NULL));
In order to do so you also need to include time.h.
Try to use
srand ( (unsigned int)time(NULL) );
at the beginning of main.
Do not forget to Include
#include <ctime>
or
#include <time.h>
From the docs:-
In order to generate random-like numbers, srand is usually initialized
to some distinctive value, like those related with the execution time.
For example, the value returned by the function time (declared in
header ) is different each second, which is distinctive enough for
most randoming needs.
#include <stdlib.h>
#include <stdio.h>
header file that has the srand(time(NULL)) function in it
#include <time.h>
.
int main (void)
{
srand(time(NULL));
seeds the random generator
int guess, tries = 6;
int number = 1+(rand()%100);
printf("Pick a number between 1 and 100:");
scanf_s("%d", &guess);
while(tries > 0 && guess != number)
{
if(guess > number)
printf("Too high");
else
printf("Too low");
puts(". Guess again:");
scanf_s("%d",&guess);
tries--;
}
if(guess == number)
puts("You win!");
else
puts("You lose");
}