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 this line -
if (UserGuess = RandomNum)
to this -
if (UserInput == RandomNum)
The first one assigns the user input stored in RandomNum into UserGuess, which is then converted to either true or false implicitly, and then the truth value of the if condition is checked by the compiler. I am assuming that you are entering non-zero value as your program input. If this is the case, then C will consider it as true. In fact, any non-zero value (whether positive, negative or fractional) is considered to be true by C.
The second expression checks for equality of two variables, rather than assigning one to another. So, you will get the desired behavior.
You are confusing = with ==
if (UserGuess = RandomNum) will not give the boolean result which you want to check that whether the guess is equal to random no generated..
Use
if (UserGuess == RandomNum)
Your if is incorrect. == is equality, = is assignment.
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");
}
Are you sure that atoi() function takes an integer argument ?
because atoi() function is used to convert string to integer.
Read this article.
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've been at this project for hours and hours trying to figure this out but I'm to the point of brain dead where everything I read leaves me confused.
The idea is to enter a number and the program will tell me whether it is right or wrong. Every single time, the end response after I enter a number is that the number is too low.
Also, the final answer states that the answer is too low and that it's correct at the same time.
Finally, this thing is suppose to ask again if the number entered is incorrect, yet I have no knowledge of how to do this.
Literally, the tiniest advice is much appreciated at this point. It's been a long, groaning night.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
//new function
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
//new function
int randomNumber(){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return 0;
}
//new function
int guessInput(){
int guess, range;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return 0;
}
//new function
int wrongAnswer(){
int guess, number;
if(guess < number)
{
printf("Try again, your guess is too low\n");
return 0;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit to high\n");
return 0;
}
return 0;
}
//new function
int correctAnswer(){
int guess, number;
if(guess == number)
printf("Great job! That time you got it right!\n");
return 0;
}
int main(){
welcomeMessage();
randomNumber();
guessInput();
wrongAnswer();
correctAnswer();
}
You're not actually passing the value of guess to wrongAnswer() or correctAnswer(). guess in those two functions is uninitialized and doesn't contain the value stored in guessInput(). This is why wrongAnswer tells you that the guess is too low and correctAnswer tells you that it's correct.
You'll also want to remove the number declaration within those functions. You have a global number right now that stores the random number, but the new number variable declared within your functions will take precedence -- it's uninitialized and doesn't contain the random number like you think it does.
You may want to adjust your wrongAnswer() and correctAnswer() functions to take guess as an integer argument, and remove the guess and number declarations within those two functions. Something like
int wrongAnswer(int guess);
int correctAnswer(int guess);
You may also want to consider having your guessInput() function return the value of guess. Try something like
int guessInput()
{
int guess;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return guess;
}
int main()
{
...
int guess = guessInput();
wrongAnswer(guess);
correctAnswer(guess);
...
}
This way you're passing the value of guess to your two functions so that they can actually evaluate whether the number is correct or incorrect.
You'll also want to look at the value of your return functions. Right now they aren't really telling you anything, and they return 0 regardless. Consider changing them to return 0 if the guess was correct and return 1 if the guess was incorrect.
int correctAnswer(int guess)
{
if(guess == number) {
printf("Great job! That time you got it right!\n");
return 0;
} else {
return 1;
}
}
With this information you can create a while loop to continually ask the user for input until they input the correct answer. Something like
int main()
{
...
int is_correct = 1, is_wrong = 1;
int guess;
while (is_correct == 1) {
guess = guess_input();
is_wrong = wrongAnswer(guess);
is_correct = correctAnswer(guess);
}
...
}
The while loop above will call each of the three functions, forever, until the user guesses the correct input. It evaluates is_correct == 1, constantly checking the value of is_correct, and repeating itself. When is_correct == 0 the loop will break and your program will terminate. This is where the return values I mentioned above come in -- a return value of 0 indicates a correct answer and will allow your program to stop. A return value of 1 will repeat the loop. There are other ways to do this, but it may help while you're starting out.
Hopefully this helps you out. I'd also consider redesigning your wrongAnswer() and correctAnswer() functions -- do you really need two? Could you reduce that to one function?
The Most basic issue that i see with the program is that you are not passing values to the functions. Each function is just working in itself and the value or should i say the 'number' it has to work with is not being passed into them.
You can use global variables or pass the values directly. This is what i would do:
The input function:
int guessInput(){
int guess, range;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return guess;}
The Random Number Generator Function:
int randomNumber(){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;}
The Answer Function: ( you really don't need 2 functions for this )
int Answer(int guess, int number){
int counter=0;
if(guess < number)
{
printf("Try again, your guess is too low\n");
counter=1;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit to high\n");
counter=1;
}
else if(guess == number)
{
printf("Great job! That time you got it right!\n");
counter=2;
}
return counter;}
Now that all your functions can accept variables, Modify the Main function
int main(){
int number=0;
int guess=0;
int answr=0; // This does not have to exist but since your doing a return.
welcomeMessage();
number=randomNumber();
guess=guessInput();
Do {
answr=Answer(guess,number);
}(while answr<2)
}
So when the counter reaches 2, which means that the answer is right, the while loop will stop when the correct answer is guessed by the user.
PS: You may need to polish my code a bit since im also in a brain dead mode atm. :D
I'm trying to make a program that generates a random number, asks the user to guess and then responds whether or not he got it right. For some reason, regardless of wether the user puts in a digit or not, it responds as if he didn't. Any ideas? thanks for helping out a beginner :)
#include<stdio.h>
#include<ctype.h>
#include<time.h>
main()
{
char iRandomNum = '\0';
int iResponse = 0;
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("Guess the number between 1 yand 10 : ");
scanf("%d", &iResponse);
if (isdigit(iResponse) == 0)
printf("you did not choose a number\n");
else if (iResponse == iRandomNum)
printf("you guessed correctly\n");
else
printf("you were wrong the number was %c", iRandomNum);
}
isdigit() takes the ascii value of a character and returns 0 if it's not a digit and non-0 if it is.
You are passing to it an integer value which is not necessarily an ascii value, you don't need to check if it's a digit since you read it with scanf().
If you want to make sure scanf() did read a number, check the return value of scanf() instead.
Try this
if (scanf("%d", &iResponse) != 1)
printf("you did not choose a number\n");
instead of the if (isdigit( ...
One more thing, main() must return int.
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;
Can someone please help me figure out what is wrong with my program it is prety complex for me. It is a number guessing game where two player can play. It starts by saying which player goes first and the player then has to input his number either 1 or 2 and then enter a guess or either pass (players can't pass more than 3 times or twice in a row). It is working very good except that everytime player 1 starts it asks him for a guess twice in a row bu then works fine, and when player 2 starts it alternates like it should like this:
And this is my code It quite a lot of code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int playerNumber = 0;
int number = 0;
int playerInput = 0;
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;
srand(time(NULL));
playerNumber = 1 + rand() % 2; /* Random number is generated */
srand(time(NULL));
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
printf("\nIt's player's %d turn\n", playerNumber);
printf("Player Number?\n");
scanf("%d", &playerInput);
while (playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (playerA != playerNumber)
playerB = playerNumber;
if (i%2 == 1) {
playerNumber = playerA;
}
else {
playerNumber = playerB;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (playerNumber == playerA){
passB = passB -1;
printf("Player 2 has %d more 'Pass' left!\n", passB);
}
else{
passA = passA -1;
printf("Player 1 has %d more 'Pass' left!\n", passA);
}
}
else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is to low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is to high */
printf("Your guess was to high.\n ");
else /* is the guess is equial to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}
First of all, you should use consistent indentation. That will make it easier to read your code.
Second, you should use newlines and whitespace to group like-lines together. Think of writing code like writing prose, and newlines as ways to separate paragraphs. You don't double-space almost anything, because it wastes space and is harder to read (people aren't used to it) so don't double-space your code.
Third, your use of the playerA and playerB variables is an OK concept, but there are better ways to do it. The typical convention in C/C++ is to use a #define for magic numbers, with all caps - #define PLAYER_A 1. Following this convention will make your code more readable. Also, since your players are "1" and "2" it is more readable to use #define PLAYER1 1 or PLAYER_1.
You use the variable "i" but the convention for using variables named i, j, k, m, or n is as loop counters that are incremented either at the top of the loop or at the bottom of the loop. Incrementing the loop counter in the middle of the loop makes it much easier for the counter to get lost. Move the increment to the top or the bottom.
Do the work by hand to see what your variables are as the program executes. Your teacher has done this in class. Just write down each variable and write its value next to it, then change the variables as they will change while the program executes. This technique will help you fix other difficult bugs in the future, rather than me giving you the answer.
You have an infinite loop in your code,
your code given below is wrong,
while(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
It should be,
if(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}