I have just started my Intro to Programming class (so please bear with me) and I am a bit stuck on one of the first assignments.
I am supposed to code a number guessing game to store a random number between 1 & 10 into a variable, prompt the user for a number, & notify if user guessed the same number or not.
I have been messing with it for some time now, and the code has changed quite a bit from what I started with. Currently, the program is saying "Congrats, you're a winner" no matter what I guess...
If anyone could just point me in the direction of what I am doing wrong, that would be great.
THE CODE HAS BEEN EDITED SINCE THE ORIGINAL POSTING OF QUESTION
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Declare Variables
int RandomNum;
int UserGuess;
//Initialize Variables
RandomNum=0;
srand ( (unsigned)time ( NULL ) );
char UserInput = 'a';
int a = UserInput;
//Generate RandomNum
RandomNum = (rand() % 10)+1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}
Change the type of UserInput
, remove UserGuess
and the spurious call to atoi()
, and it'll work:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
//Declare Variables
int RandomNum;
int UserInput; // Changed to int
//Initialize Variables
RandomNum = 0;
UserInput = 0; // Changed initialization
srand((unsigned) time(NULL));
//Generate RandomNum
RandomNum = (rand() % 10) + 1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}