Monty hall show simulation unexpected results - c

#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf ("The door the host picked is %d\n", hostDoor);
do
{
printf("Do you want to switch doors? Please enter in the door you want:\n", hostdoor);
scanf("%d", &option);
if (option > 3 || option <= 0)
{return 0;}
}while (option == hostDoor);
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Hi, this is my version of the monty hall game show, im getting unexpected results though.
sometimes when I enter in a door for my option it just brings me back to the "pick one of the three doors infront of you" statement, when it should tell me if i have won or lost.
I think this is because the "option" door is equal to the "hostDoor.
I thought having "option != hostDoor" would fix it but it does not.
If i am correct in that assumption how can I fix it? If not why is it not working and how can I fix it?

To simulate correctly, OP needs to show the host door.
do {
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) {
return 0;
}
} while (option == hostDoor);
// instead of
#if 0
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
if (option > 3 || option <= 0 ) { return 0; }
#endif
To deal with OP " it should tell me if i have won or lost." problem, change
else if (option == remainingDoor)
to
else
Your scanf("%d", &option) is OK. I prefer the fgets()/sscanf() combo and its alway useful to check the result of scanf() family, but that is not your issue here.

Its because of these:
scanf ("%d", &pickedDoor);// reads \n after the last input
scanf("%d", &option); // reads \n after the last input
**option != hostDoor; // completely useless .. get rid of it**
I would suggest putting a getchar() after each scanf to get rid of the \n character
so something like this:
#include <stdio.h>
#include <time.h>
int main (void)
{
int pickedDoor, remainingDoor, hostDoor, winningDoor, option, games = 0, wins = 0;
char collect; //variable to collect any extra input like \n
float frequency = 0;
srand (time(NULL));
while (1)
{
printf ("Pick one of the three doors infront of you, which do you want?\n");
scanf ("%d", &pickedDoor);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (pickedDoor > 3 || pickedDoor <= 0)
{
break;
}
winningDoor = rand() % 3 + 1;
do
{
hostDoor = rand() % 3 + 1;
} while (hostDoor == pickedDoor || hostDoor == winningDoor);
do
{
remainingDoor = rand() % 3+1;
} while (remainingDoor == pickedDoor || remainingDoor == hostDoor);
printf("Do you want to switch doors? Please enter in the door you want:\n");
scanf("%d", &option);
collect = getchar(); // get rid of the \n from the input stream
printf("collect = %c\n",collect);
if(collect!='\n'){ // is it actually a \n or did you take in something else
putchar(collect); // if it isn't \n put it back
}
if (option > 3 || option <= 0 )
{
return 0;
}
if (option == winningDoor)
{
printf("You Won!\n");
wins++;
}
else if (option == remainingDoor)
{
printf("YOU LOSE!\n");
}
games++;
}
frequency = ((float) wins / games) *100;
printf ("The number of games that you won is %d\n", wins);
printf ("The frequency of winning is %.0f%%\n", frequency);
return 0;
}
Another more efficient way would be to use fgets or to have error checks on scanf() itself

srand and rand belongs to stdlib header file
#include<stdlib.h> // include this header file
option != hostDoor; // this statement does not do anything
and your else if (option == remainingDoor) should be else { printf("you lose");}

Related

Is there a way to make two while loop condition

#include <stdio.h>
#define MAXLIMIT 1000
#define MINLIMIT 1
int main()
{int number = 0, valid=0;
do {
printf("Player 1, enter a number between 1 and 1000:\n");
scanf("%d", &number);
valid = number >= MINLIMIT || number <= MAXLIMIT;
if (!valid) {
printf("That number is out of range.\n");
}
} while (!valid);
int guess = 0, chance = 10;
// Allow player 2 to guess and check
do {
printf("Player 2, you have %d guesses remaining\n", chance);
printf("Enter your guess:\n");
scanf("%d", &guess);
if (guess < number){
printf("Too low.\n");
} else if (guess > number) {
printf("Too high.\n");
} else if (guess == number){
printf("Player 2 wins.\n");
}
else if (guess != number && chance == 0)
printf("Player 1 wins.\n");
} while (guess != number && chance > 0);
}
This is currently my code. I'm stucked at the last where once the user has use up their 10 chances, Player 1 wins. Is there anyway for two while loop condition to happen?
SUGGESTION:
Refactor your code:
Store information about each player (e.g. "name" and "#/guesses") in a struct.
Create an array of players: struct player players[2];
Move your "make a guess" code into a function: void guess(int number, struct player * player).
Whenever you call "guess()", simply check if the #/guesses for that player has been exceeded.
For starters the logical expression
valid = number >= MINLIMIT || number <= MAXLIMIT;
is invalid. You need to use the logical AND operator instead of the logical OR operator
valid = number >= MINLIMIT && number <= MAXLIMIT;
This syntactically incorrect part with do statement
do {
while (guess != number && chance = 0)
printf("Player 1 wins. \n")
}
is redundant.
It is enough to write
if ( guess != number )
{
printf("Player 1 wins. \n");
}
EDIT: After you changed your code in the question then write the if statement within the do-while loop like
if (guess < number){
printf("Too low.\n");
} else if (guess > number) {
printf("Too high.\n");
} else
printf("Player 2 wins.\n");
}
And after the do-while loop write
if ( guess != number )
printf("Player 1 wins.\n");
I won't address the errors in the posted code(s) because the details of this question keeps changing.
Is there anyway for two while loop condition to happen?
Of course we can write suitable conditions to end the do while loops, but it seems to me that it would be more simple to break out when the second player guesses the number and print the winner only after.
int chance = 10;
do {
printf("Player 2, you have %d guesses remaining\n", chance);
printf("Enter your guess:\n");
int guess = 0;
scanf("%d", &guess);
if (guess < number){
printf("%d is too low.\n", guess);
} else if (guess > number) {
printf("%d is too high.\n", guess);
} else { // No need to check equality.
printf("%d is correct\n", guess);
break; // <-- Exit the loop.
}
--chance; // Don't forget to update this.
} while ( chance > 0 );
if ( chance == 0 ) {
printf("Player 1 wins.\n");
} else {
printf("Player 2 wins.\n");
}

I don't understand why a part of my code isn't connecting to the rest

I have an assignment for a coding class where I have to create a code for the rock, paper scissors game, with different functions, calling rock 1 and paper 2 and scissors 3.
I also have to create a menu, then have the person chose, save that, then have the computer generate a random number and then print what they played, what the computer played and who won.
However, the last part isn't connecting, and I don't understand where I went wrong, so I'm really really lost and I would really appreciate any help.
For reference here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float response, choice;
int playerInput() {
printf(" For rock press 1\n ");
printf("For paper press 2\n ");
printf("For scissors press 3\n ");
printf("What would you like to play? ");
scanf("%f", &response);
return response;
}
int computerChoice() {
int lower = 1, upper = 3, count = 1;
srand(time(0));
printf("The random number that: ");
for (int i = 0; i < count; i++) {
int choice = (rand() % (upper - lower + 1)) + lower;
printf("the computer chose is %d ", choice);
}
return choice;
}
void displayWinner() {
if (response == choice) {
printf("You tied, lets play again");
}
if (choice == 1 && response == 2) {
printf("you won");
}
if (choice == 1 && response == 3) {
printf("computer won");
}
if (choice == 2 && response == 1) {
printf("computer won");
}
if (choice == 2 && response == 3) {
printf("you won");
}
if (choice == 3 && response == 1) {
printf("you won");
}
if (choice == 3 && response == 2) {
printf("computer won");
}
}
int main(void) {
int pinput, cinput, dinput;
pinput = playerInput();
cinput = computerChoice();
displayWinner();
return 0;
}
int choice =
But why declare a local with the same name as a global. I suggest that's your first mistake.
On fixing it you'll find the next line prints garbage because it's now printing a %d from a float (that got widened to a double).

Craps game - scanf automatically input huge number

The instructions for the part of the project I am having trouble with are:
"Playing" the game:
A second function playing() will be used to play a single game of craps until the player either wins or loses a bet, based upon the rules given above. This function should be modify the current $ amount of the player's bank roll according to the game result, modify the array values of the player won or lost, and whether the player bet for or against him/herself. Within the function, the player is asked whether s/he would like to place a bet. If so, the player must choose whether to bet "for" or "against" him/herself (see game rules above). The player then "rolls the dice" (simulated by a call to the dice-rolling function rolling()). This should be done interactively (via a key press from the player), rather than simply having the program continuously roll the dice until the game is over. After each roll, this function should report the two random dice values and the sum of the two. If, after the first roll, the game is not over, the player should be asked whether s/he would like to double the amount of the bet. When a roll causes the end of a game, the player is notified whether s/he won or lost money in that game overall, and the amount won or lost. In all other cases, the player is notified that s/he needs to roll again.
I have to code in a craps game that asks user for a bet amount and then they play craps. They have an initial bank roll of $100. I have to scan a bet amount in using scanf but it keeps making my bet amount very large without any user input. Can someone please help me, I have this project due tonight.
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
//function prototype
int rolling(void);
int playing(int c_amt);//inital money $100, min bet of $5, no max except money you have
void beginning(void);
void ending(void);
int
main()
{
printf("\nWelcome to Craps! Get ready to play!");
int bank_amt = 100;
char y_n = 'n';
do
{
bank_amt = playing(bank_amt);
if(bank_amt == 0)
{
printf("\nYou bet and lost all your money! You can't play anymore. Goodbye!");
exit(0);
}
if(bank_amt != 0)
{
printf("\nYour current balance is %d %d", &bank_amt, bank_amt);
printf("\nDo you want to play again? (y/n): ");
scanf("\n%c", &y_n);
}
}
while(y_n != 'n' && y_n != 'N');
}
int
rolling(void)
{
int dice1, dice2;
char roll;
srand((int)(time(NULL))); // "Seed" random number gen. with system time
printf("\nPress enter to roll the dice!");
fflush(stdin);
scanf("%c",&roll);
dice1 = 1+rand()%6; // random num from 1-6
dice2 = 1+rand()%6; // random num from 1-6
return dice1+dice2;
}
int
playing(int c_amt)
{
char gametype, y_n = 'n';
int total, point, for_u, against_u, winlose, win = 0, lose = 0;
int moneychange, bet_amt, final_amt;
printf("\nPlease press 'f' if you are betting for yourself and 'a' if your are betting against yourself.\n");
scanf("\n%c", &gametype);
do
{
printf("\nYour current bank balance is %d.", c_amt);
printf("\nEnter the amount you want to bet: ");
scanf(" %d", &bet_amt);
printf("Bet amount: %d", bet_amt);
if(bet_amt > c_amt || bet_amt < 5)
{
printf("\nYou dont have that much money or you placed a bet less than the minimum. Please place a proper bet.");
}
}
while(bet_amt > c_amt);
if (gametype == 'f' || gametype == 'F')
{
for_u++;
printf("\nYou are betting for yourself!\nLets get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 7 || total == 11)
{
printf("\nGood job! You win :)");
winlose = 1;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("\nCraps, you lose.");
winlose = 0;
}
else
{
point = total;
printf("\nYour point is %d.", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == point)
{
printf("\nGood job! You win! :)");
winlose = 1;
break;
}
}
while(total != 7);
if(total == 7)
{
printf("You rolled a seven. You lose! :(");
winlose = 0;
}
}
}
else if (gametype == 'a' || gametype == 'A')
{
against_u++;
printf("You are betting against yourself!\nLet\'s get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 2 || total == 3 || total == 12
{
printf("Good job! You win :)\n");
}
else if (total == 7 || total == 11)
{
printf("Craps, you lose.\n");
}
else
{
point = total;
printf("Your point is %d.\n", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == 7)
{
printf("\nGood job! You win! :)");
winlose=1;
break;
}
}
while(total != point);
if(total == 7)
{
printf("You rolled a seven before making your point. You lose! :(");
winlose = 0;
}
}
}
if(winlose == 1)
{
final_amt = bet_amt + c_amt;
win++;
}
else
{
final_amt = c_amt - bet_amt;
lose++;
}
printf("Final amount is %d.", final_amt);
return final_amt;
}
Here is sample output:
Welcome to Craps! Get ready to play!
Please press 'f' if you are betting for yourself and 'a' if your are betting against yourself.
Your current bank balance is 100.
Enter the amount you want to bet: Bet amount: -1219958512
You dont have that much money or you placed a bet less than the minimum. Please place a proper bet.Final amount is 1219958612.
Your current balance is -1074871812 1219958612
Do you want to play again? (y/n):
Your formatting needs a lot of fixing to understand. However, the real issue is a buffer overflow, caused by not allocating enough memory to the char. Instead, I would suggest using simple int values like 0 and 1 to determine the player's choices.

If and if else statements working, but not else

I am making a number guessing game program and am having some trouble with my else statements. In the main block where the number is trying to be guessed, the if and if else statements work, but the else statement does nothing. I am trying to make it where a number outside of the range 0 < number < 100 trigger the else statement.
Furthermore, I am trying to make the game repeat itself if '1' is entered but no matter what is entered, the program crashes.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess > 0)
{
if (guess < 52)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
}
else if (guess <100)
{
if (guess > 52)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
}
else if (guess == 52)
{
printf("Correct! You win!\n");
attempt = 0;
}
else
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
When you use if else if without brackets, make sure it can't be ambigous.
When you do :
if (true)
if (true)
{
}
else if (false)
{
}
How to know if the else if correspond to the first or the second if ? That's why everyone yell at you to put brackets.
if (true)
{
if (true)
{
}
}
else if (false)
{
}
Corrected and simplified version :
Your program crashes because you forgot the & sign inscanf("%d", &playAgain);.
The logic in your program is wrong, you intermix the test if the number is lower, equal or higher than the input with the test if the input is lower than 0 or higher than 100.
In this corrected version the "invalid input" problem is separated from the actuel "number guessing" problem.
Furthermore the number to be guessed (52) is nor longer hard coded but a variable numbertobeguessed is used instead. Later you should enhance the program so that a random number is generated.
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int numbertobeguessed = 52 ;
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess < 0 || guess > 100)
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
else
{
if (guess < numbertobeguessed)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
else if (guess > numbertobeguessed)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
else
{
printf("Correct! You win!\n");
attempt = 0;
}
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", &playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
the else statement which gives message "Invalid input: Please enter an integer between 1 and 100:\n" is considered as the else part of inner most if-else-if statement. there fore that statement is never executed as the execution enters that if-else-if statement only if 0 < guess < 100. so use {} properly to make the proper combination of if-else statements.
Your nesting is wrong. Put brackets for each if and else to make your code work (quickfix), and use proper indentation to make it readable to humans (if you wish).
Here's an example of how things can go wrong (pseudo code):
a = 4
if (a > 0)
if (a < 3)
a = 2
else
a = 3
What do you expect is the end value of a?
Anyway, your:
if (guess > 0)
if (guess < 52)
should become this:
if (guess > 0 && guess < 52)
and your:
else if (guess <100) // this is where the problems start
if (guess > 52)
should become:
else if (guess < 100 && guess > 52)
and your code will work.
hope this helps
#include <stdio.h>
#include <stdlib.h>
int main()
{
int guess; //variable to hold the number from player
int attempts = 6;
char play = 'y';
do
{
while(attempts)
{
printf("\nEnter you guess: "); scanf("%d", &guess);
attempts--;
if(guess>0 && guess <100 )
{
if(guess>52)
printf("\nThat's not it. Try something lower than that.");
else if(guess<52)
printf("\nThat's not the number. Try something higher than that.");
else if(guess==52)
{ printf("\nYou got it!. You won the game.");
attempts = 0; //we're setting it to zero; we don't want the loop to run anymore
}
}
else
printf("\nNumber enter is not in range!");
}//end of while loop
printf("\nDo you want to play again? (y/n): "); scanf("%c", &play);
}while(play=='y' || play=='Y'); //run till player enter 'Y'
return 0;
}

Random number game C

The game works fine my first time through, although; the second time it only gives you two lives... I have tried to change the number of lives but still can't figure out what I'm doing wrong.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%5 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("\n%d",&num1);
x++;
if(num1 > 0 && num1 < 5)
{
do
{
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++;
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++;
}
scanf("%d",&num1);
}while(num1!=r && x <3);
if(num1 == r)
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
else if(num1 != r)
{
printf("\nBetter luck next time!");
}
printf("\n\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}
else
{
printf("Sorry! Try again : ");
scanf("%d",&num1);
}
}while(replay == 'y'|| replay == 'Y');
}
else if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
else
{
printf("Sorry, invalid data! ");
}
return 0;
}
There are all kinds of issues with you code (most of them are minor in terms of programming). Most of the errors are typos in what you want done via this question and what you printf().
As is, this code will random between 1-25, accept an input of any valid int, see if you matched it, and only give you 5 tries. (I didn't add error checking to enforce that the input is between 1-25. That should probably be added.)
I commented my code below with all my changes and went by that you had in the printf()s.
Note: See my comments above for explanations of my changes since I already pointed them out. I also formatted it so its a little more easy to read.
Note2: I did this quickly using an online compiler. If you find anything wrong with this or not working as you'd like, just comment below and I'll address it.
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%25 +1;
printf("\n\nEnter a number between 1 and 25 : ");
scanf("%d",&num1);
do
{
printf("r = %d\n", r);
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++; //Increment x if wrong guess
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++; //Increment x if wrong guess
}
scanf("%d",&num1);
}while(num1!=r && x < 5); //If x is 5 or more, they ran out of guesses (also, you want an && not an ||)
if(num1 == r) //Only print "winner" if they won!
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
printf("\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}while(replay == 'y'|| replay == 'Y');
}
printf("Thanks for playing! ");
if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
return 0;
}
There are a combination of two problems. The first is that you're not breaking out of the "for" loop when the number matches. Therefore the match is only checked on every third guess.
The second problem is in this logic check:
}while(num1!=r || x <= 3);
We see that this turns into "true" if the for loop is broken out of early.

Resources