I am a beginner coder and I need a few ideas on how my code can output the right syntax.
If I input number < 25
Outputs and extra(s) ", " because it still runs through and sees that (amount_left > 0).
How would I make it so if there doesn't exist a quarter or dime it does not output the ", "?
#include <cstdio>
#include <iostream>
using namespace std;
void compute_coins(int coin_value, int& number, int& amount_left);
int main(){
int amount_left, number;
while(amount_left > 1 || amount_left < 99){
cout << "Enter number of cents (or zero to quit):" << endl;
cin >> amount_left;
if (amount_left == 0){
break;
}
else{
cout << amount_left << " cents can be given as ";
compute_coins(25, number, amount_left);
if (number == 1){
cout << "1 quarter";
}
else if (number > 0){
cout << number << " quarters";
}
if (amount_left > 0){
cout << ", ";
}
compute_coins(10, number, amount_left);
if (number == 1){
cout << "1 dime";
}
else if (number > 1){
cout << number << " dimes";
}
if (amount_left > 0){
cout << ", ";
}
compute_coins(1, number, amount_left);
if (number == 1){
cout << "1 penny";
}
else if (number > 1){
cout << number << " pennies";
}
std:: cout << ".";
}
cout << endl;
}
return 0;
}
void compute_coins(int coin_value, int& number, int& amount_left){
number = amount_left/coin_value;
amount_left = amount_left - (number * coin_value);
}
The expectation is that a period, and exactly one period must come after all the amounts get printed out.
Therefore, it makes no logical sense to write complicated code that tries to figure out whether it should print a period before the rest of the code, for all the remaining denominations, is done.
Just get rid of that code that prints all those periods, inside all of those awkward if/else statements.
At the very end of everything, simply execute
std::cout << ".";
No ifs, elses, or buts.
Simply focus on the problem of writing out the counts of all the denominations, correctly separated by commas. Forget about the trailing period. Just focus on formatting a comma-separated list of all possible denominations. Put the trailing period out of your mind.
Then, once you get all of that working, simply append
std::cout << ".";
at the end, and call it a day. This is a 100% guaranteed, or your money back, way to end up with exactly one period at the end of your output.
Related
#include <iostream>
#include <string>
int main()
{
int hun;
std::cout << "Please pick a number between 1 and 100 \n";
std::cin >> hun;
if (hun > 50)
{
std::cout << "Your number is greater than 50. ";
}
if (hun < 50)
{
std::cout << "Your number is less than 50. ";
}
if (hun > 100)
{
std::cout << "Pick a number LESS than 100. ";
}
else { std::cout << "Your number is equal to 50. "; }
return 0;
}
If I run it without the:
std::cout << "Pick a number LESS than 100. ";
then the program works as expected. However it doesn't work if I include it. For example if I input "13" I get both the message "Your number is less than 50, AND your number is equal to 50" ?? I don't understand why it is still executing the else statement if my IF statement was already met. This isn't an issue ONLY if I removes that 3rd IF statement.
I cannot figure out why it is just that line that is messing up. I seem to have everything written correctly, and I didn't forget the curly brackets. So why is this happening?
I'm sure it's a simple mistake. It's my first week coding and I'm doing it on my own with no outside help, so I don't have anyone to go to for silly questions like this.
While I'm here, how do I get the program to say something like "You have entered an invalid response. " When the user inputs a word or a letter? I thought about doing something like:
int word;
word = 1-100;
if (hun = word) or (hun != int?)
(But that will only subtract 100 from 1 giving me -99 and not the range, I really do not even know where to begin with this)
You need to implement if-else if- else statements:
if (hun > 100)
{
std::cout << "Pick a number LESS than 100. ";
}
else if (hun > 50)
{
std::cout << "Your number is greater than 50. ";
}
else if (hun < 50)
{
std::cout << "Your number is less than 50. ";
}
else
{
std::cout << "Your number is equal to 50. ";
}
The reason why the original code didn't work is that the else was only linked to the last if. So if a number satisfied one of the earlier if statements but not the last if it would go to both the if it satisfied and the else as the last if was not satisfied.
Additionally you must reorder it so that the more extreme cases are first. Otherwise if hun is more that one hundred but you have the condition hun > 50 then it will go to that if-else and then skip the rest.
Try this
if (hun >= 0 && hun < 50){
std::cout << "Your number is less than 50. ";
}
else if (hun == 50){
std::cout << "Your number is equal to 50. ";
}
if (hun > 50 && hun <= 100) {
std::cout << "Your number is less than 50. ";
}
else {
std::cout << "you ve entered invalid number " << hun << " . supported range is [0 - 100]";
}
// DiceRollProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int diceRoll(int max); // function definition
int getValidInteger();// function definition
int main() {
srand(time(0)); // seed the random number generator
int exitProgram = 0;
int guess, rollValue;
int maxRollValue = 6;
cout << "Hello! Let's play a dice game. Let me do the first roll for you.\n" << endl;
rollValue = diceRoll(maxRollValue);
cout << "In this roll, you got: " << rollValue << "\n" << endl;
do {
rollValue = diceRoll(maxRollValue);
cout << "What's your guess for the next roll? Enter an integer between 1 and " << maxRollValue << ": ";
guess = getValidInteger();
// TODO: Validate input
if (guess > rollValue)
{
cout << "The guess was too high!";
}
if (guess < rollValue)
{
cout << "The guess was too low!";
}
if (guess == rollValue)
{
cout << "You guessed correctly, congrats!";
}
cout << "In this roll, you got: " << rollValue << "\n" << endl;
// TODO: Evaluate result
cout << "Enter 1 to exit or any other integer to continue rolling ";
exitProgram = getValidInteger();
cout << "\n";
if (exitProgram == 1)
{
cout << "Sorry to see you go. Have a wonderful day!\n" << endl;
}
} while (exitProgram != 1);
return 0;
}
// Roll the die
int diceRoll(int max) {
int rollValue;
rollValue = (rand() % max) + 1;
return rollValue;
}
// Check if user entered an integer
int getValidInteger() {
int userInput;
cin >> userInput;
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Please enter an Integer only ";
cin >> userInput;
cout << "\n";
}
return userInput;
}
I have a dice roll guessing game, I'm trying to evaluate the users input, to make sure that they can't enter a number less than 1 and greater than 6, unfortunately, with just my if statements, they can still enter these numbers, although a string is displayed that the input is not valid, I want to make a while loop that keeps asking them to enter a valid number equal or greater than 1 and equal to and less than 6, if the user keeps inputting an incorrect number, the while loop will keep asking them for a valid number, until they do enter one, which will then run the program as normally.
First of all, inside the while loop you have dead code.
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
Within the loop body, the first if is always true and the second one is always false. You should enter in a loop when the user writes an invalid input. This happens when (userInput < 1 or userInput > 6)
After the evaluation of the while's condition, you should ask the user to write input
do {
cout << "Please enter an Integer only ";
cin >> userInput;
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}while(userInput < 1 || userInput > 6);
So your condition that will keep you in the while loop is if the person guesses too high or too low. Inside the while loop I would add the updating condition or statement that you would like to repeat. So in your case, "your guess is too high" or " your guess is too low" and ask for their input again. I am not a pro but I would keep it simple by constructing 2 while loops, one for too high and one for too low just like your if statements. literally you can just change your first two if statements to while loops and adding an few extra lines of cout to ask the person to guess again and validate their input. I hope this helped.
from what I've understood you are looking for something like this:
int main (){
int my_magic_number=(rand()%6)+1,usernumber=-1;
bool state;
while (usernumber!=my_magic_number){
cin>>usernumber;
state = (usernumber<1||usernumber>6);
while (state) {
cout<<"You entered a number outside the range [1,6] please try again\n";}
cin>>usernumber;
state = (usernumber<1||usernumber>6);
}
if (usernumber!=my_magic_number) {/* do whatever you want */}
} //while loop
} // main
This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.
I have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Well, I'll introduce myself first. I'm Ben, a 17-years old 'game-programmer' from the Netherlands who just has begun to program in C++ (started about a month ago, but programming for a year right now) (and I'm using Microsoft Visual Studio 2012 as compiler). Now, I am 'learning it myself' but I still do use a book and that book is called 'Beginning C++ Through Game Programming, Third Edition' by Michael Dawson.
I just did finish with chapter two and the last excersize was: "Write a new version of the Guess My Number program in which the player and the computer switch roles. That is, the player picks a number and the computer must guess what it is."
Here follows the code of the 'Guess My Number' Program:
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumber)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
Now, I was busy with thinking, programming testing and it just wouldn't work.
It seems I got stuck with such a infinite loop. But I can't find the problem.
Here's the code, and other ways to fix this are welcome, just keep in mind that I don't know a lot of the language. ;)
// Guess My Number 2
// The classic number guessing game with a twist
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
int secretNumberComputer = rand() % 100 + 1;
int secretNumberPlayer;
int triesPlayer = 0;
int triesComputer = 0;
int guessPlayer;
int guessComputer;
int tooHighPlayer;
int tooLowPlayer;
int correctPlayer;
int tooHighComputer;
int tooLowComputer;
int correctComputer;
int selectNumberIncorrect;
int lowerGuessComputer = 101;
int higherGuessComputer = 0;
cout << "Welcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guessPlayer;
++triesPlayer;
tooHighPlayer = (guessPlayer > secretNumberComputer);
tooLowPlayer = (guessPlayer < secretNumberComputer);
correctPlayer = (guessPlayer == secretNumberComputer);
if (tooHighPlayer)
{
cout << "Too high!\n\n";
}
else if (tooLowPlayer)
{
cout << "Too low!\n\n";
}
else if (correctPlayer)
{
cout << "\nThat's it! You got it in " << triesPlayer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctPlayer);
cout << "Now it's time for you to pick a number and then the computer will guess.\nEnter a number between 1 and 100: ";
do
{
cin >> secretNumberPlayer;
selectNumberIncorrect = (secretNumberPlayer > 100 || secretNumberPlayer < 1);
if (selectNumberIncorrect)
{
cout << "\nHey, that isn't a number between 1 and 100! Please pick a number that is: ";
}
else
{
break;
}
} while (selectNumberIncorrect);
guessComputer = (rand() < lowerGuessComputer && rand() > higherGuessComputer);
cout << "\n\nNow the computer is going to try to guess your number:" << endl;
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
tooHighComputer = (guessComputer > secretNumberPlayer);
tooLowComputer = (guessComputer < secretNumberPlayer);
correctComputer = (guessComputer == secretNumberPlayer);
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
}
else
{
cout << "Error, check code!\n\n";
}
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
if (triesComputer < triesPlayer)
{
cout << "You lost against the computer!\n\n";
}
else if (triesComputer > triesPlayer)
{
cout << "You won!\n\n";
}
else
{
cout << "It's a tie!\n\n";
}
cout << "Thank you for playing! Goodbye!" << endl;
return 0;
}
In this block you aren't checking the computer's guess for correctness (assigning correctComputer), so the loop continues forever, unless it guessed correctly the first time.
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
Your second do loop never recalculates the computer's guess.
i.e. you have the computer guess one number before the do loop, then in the loop you keep checking if that one guess is too high or too low, never recalculating its value. It'll obviously never end.
You need to do the computer's guess calculation inside the second loop.
EDIT
Also, this logic is incorrect:
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
The guess will always be 0 or 1 because the result of the right-hand-side operation is a boolean. In fact, I don't know what you're trying to do there. You're performing && between an integer and a boolean. I also don't understand why you are calculating two different guesses - you should calculate one number within the range of the higher/lower parameters you were given.
In addition to what Kevin Tran wrote, please check the valid input type for cin.
Imagine someone typing characters instead of integers.
so
cin >> guessPlayer;
can be written as
if (cin >> guessPlayer) {
// Do you logic here
}
else {
cout<<"Enter numbers only. :)";endl;
continue;
}
Hope this helps.
Instead of analyzing the code you posted which has numerous flaws, let's just think about what your program has to do: The user will pick a random number, and the computer will try to guess that number.
So, your program flow should go like this:
The computer picks a random number. It prints it out and asks the user to choose if the number is too high, too low or correct. (i.e. by asking the user to type '1' if too high, '2' if too low or '3' if it's right).
If the user types '3' then obviously you're done.
If it's too high, the computer picks a new random number (smaller than it's last guess) and tries the above logic again.
If it's too low, the computer picks a new random number (greater than it's last guess) and tries the above logic again.
Now let's try and implement some code that implements the above:
using namespace std;
int main()
{
int range_low = 0; // The number the user picked is greater than this
int range_high = 100; // The number the user picked is smaller than this
srand(static_cast<unsigned int>(time(0)));
do
{
// We want to generate a random number between range_low and range_high. We do this
// by generating a random number between zero and the difference of "low" and "high"
// adding it to low and adding one more.
int guess = range_low + ((rand() % (range_high - range_low)) + 1);
cout << "I'm guessing your number is " << guess << "... how did I do?" << endl
<< " [1: too high, 2: too low, 3: you got it!] ";
// Now let's see how we did...
int choice;
cin >> choice;
if(choice == 3)
{
cout << "Be amazed at my psychic powers! For I am a computer!" << endl;
break;
}
if(choice == 2)
{
cout << "Hmm, ok. I was sure I had it. Let's try again!" << endl;
range_low = guess;
}
if(choice == 1)
{
cout << "Really? Ok, ok, one more try!" << endl;
range_high = guess;
}
} while(true);
return 0;
}
Here are two exercises for you to improve the above:
First, try to compare the logic of this code against the logic of your code and see where your code differs - try to understand why it was wrong. It will help to try to execute the program using pen and paper, just like you were a computer that understood C++.
Second, try to add code to ensure that the computer never guesses the same number twice.