-1

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;

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user233539
  • 13
  • 1

3 Answers3

1

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.

Raghu Srikanth Reddy
  • 2,703
  • 33
  • 29
  • 42
1

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:

  1. The recommended signature of main() is int main(void).
  2. Always initialize your local variables. Good practice.
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Morb
  • 534
  • 3
  • 14