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");
}
Related
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.
I want to make a simple program in which the rand() function generates a random number out of 1,2,3 and the user is asked to predict the number. if the user predicts the number correctly then he wins otherwise he looses.
Here's the program-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int game;
int i;
int x;
printf("enter the expected value(0,1,2)");
scanf("%d\n",&x);
for(i=0;i<1;i++){
game=(rand()%2) + 1
if(x==game){
printf("you win!");
}
else{
printf("you loose!");
}
} return 0;
}
Some issues with your code:
Point 1:
scanf("%d\n",&x);
should be
scanf("%d",&x);
Point 2:
for(i=0;i<1;i++)
this for loop is practically useless. It only iterates one. either use a longer counter, or get rid of the loop.
Point 3:
It's better to provide a unique seed to your PRNG. You may want to use srand() and time(NULL) in your function to provide that seed.
Point 4:
game=(rand()%2) + 1
should be
game = rand() % 3; // the ; maybe a typo in your case
^
|
%3 generates either of (0,1,2)
Point 5:
When you use % with rand(), be aware of modulo bias issue.
Note:
The recommended signature of main() is int main(void).
Always initialize your local variables. Good practice.
Remove \n from your scanf()
scanf("%d\n",&x); to
scanf("%d",&x);
and place a semicolon(;) after game=(rand()%2) + 1;
it works.
Your for loop is not required here.
You didn't ask any question but I guess it is "Why my rand() function doesn't work?"
You need to add these lines
#include <time.h>
and the random initialization at the beginning of the main function:
srand(time(NULL));
Which should give:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int game;
int i;
int x;
printf("enter the expected value(0,1,2)");
scanf("%d",&x);
for(i=0;i<1;i++){
game=(rand()%2) + 1;
if(x==game){
printf("you win!");
}
else{
printf("you loose!");
}
} return 0;
}
Edit: there are other problems as Sourav said
I was trying to do a "Guess the number" game that would use a verification to see if the number is low, high or equal to the random number. I want to do a loop verification that will say if the number is to high and to try again!
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <cs50.h>
int
main(void)
{
srand(time(NULL));
int skittles = rand() % 1024;
printf("%d\n", skittles);
printf("choose a number betwen 1 to 1024\n");
int numpessoa = GetInt();
printf("%d\n", numpessoa);
if (numpessoa < skittles)
{
printf("numpessoa < skittles");
numpessoa = GetInt();
}
if (numpessoa > skittles)
{
printf("numpessoa > skittles");
numpessoa = GetInt();
}
if (numpessoa == skittles)
{
printf("numpessoa == skittles");
}
return 0;
}
If this is an homework,you shouldn't ask its solution directly.
I only can provide some pseudocode.
loop forever
get user's guess
check guess against answer
guess differs answer ,then provide some hints
guess equals answer,tell user he/she is right and break out of this loop
And there is an another bug in your code.
The 1024 modulo of an random integer is between 0 and 1023.
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:
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..