Tried to write a program in C to say the amount of times you guessed the right number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, searchNumber, Number, rightGuess;
rightGuess = 0;
printf("Give your number: ");
scanf("%d",&searchNumber);
printf("\n\n Give 10 numbers: ");
for(i=1;i<=9;i++){
scanf("%d \n",&Number);
if(Number == searchNumber){
rightGuess++;
}
}
printf("You guessed the number %d times",&rightGuess);
return 0;
}
However every time I run it, it says I guessed the number 6356736 times. Even though I only entered a number 0 times. Any help?
A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N in a maximum of 10 attempts. The game will end after 10 attempts and if the player failed to guess the number, and then he loses the game. Machine: Lower number please!
During the game, a player tells the computer his assumption about a number, and the computer tells if the player is correct. If his number is less or more than the secret number, the computer informs the player, and the player tries again. The player can also end the game at any time.
Else If the user guesses a number that is less than the randomly chosen number, the user receives the message “You guessed too low !!” And if the user guessed in a minimum number of guesses, the user gets a congratulatory “You guessed the correct number !!!!!!!” output along with the number of guesses.
In this game, the computer generates a secret number in the range of 1 to 100, and the player has to guess it. The game has three difficulty levels. A player’s chances of guessing are limited by the level they choose.
Maybe you made a mistake in printf()
.
If there is a variable named var
, &var
means the memory address where variable var
is. Maybe the number 6356736
you saw in your program is the memory address, not the value in variable var.
You will have to change this line in order to print the value of variable rightGuess
printf("You guessed the number %d times", &rightGuess);
To this line.
printf("You guessed the number %d times", rightGuess);
Your call to printf
ought to be
printf("You guessed the number %d times", rightGuess);
i.e. don't pass a pointer to rightGuess
in correspondence to the %d
format specifier. Currently the program behaviour is undefined! (It could well be outputting the address of rightGuess
which accounts for the large number - but don't ever rely on that; you need to use %p
to output pointer addresses.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With