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;
}
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.
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:
main()
is int main(void)
. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.