0

I have written a program but it always gives the same number (41). Why does not it change next time I play?

Second question is: How can I limit the answer between 2 numbers?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int magic,guess;
    char ans='y';
    magic=rand();
    printf("\t\t\tgame(guess the number)\n");
    do{
        printf("guess the magic number\n");
        scanf("%d",&guess);
        if(guess==magic){
            printf("\n*****Right*****\n");
            printf("%d is the magic number.",magic);
            getch();
            ans='n';
        }else{
            printf("\n*****Wrong*****\n");
            if(guess>magic)
            printf("your guess is too high\n");
            else printf("your guess is too low\n");
            printf("do you want to continue?\n");
            ans=getch();
        }
    }while(ans=='y');
    return 0;
}

I want to limit answer between 50 and 500. How can I do that?

Masoud Mohammadi
  • 1,721
  • 1
  • 23
  • 41

2 Answers2

1

put srand (time(NULL)); as the very first line of your main() function and let the magic start :)

now .... rand() gives you number in the range 0 to RAND_MAX

so lets say you want to limit it between x and y(inclusive)(x < y)

then int rand_num = rand() %(y-x+1) + x; would be your solution

Cheers :)

Dhaval
  • 1,046
  • 6
  • 10
0

Seed the random number generator with srand - http://www.cplusplus.com/reference/cstdlib/srand/

Use something like the process ID and/Or the current time

Ed Heal
  • 59,252
  • 17
  • 87
  • 127