Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
hey I've just started on a school project but can't figure out why the code just ignores a large chunk of itself.
(also the code is part of a function inside of "math.h")
ill paste the whole segment here so that debugging it is easier.
#include <iostream>
#include <chrono>
#include <thread>
#include <algorithm>
using namespace std;
using namespace chrono;
using namespace this_thread;
class math {
private:
unsigned short pts;
public:
unsigned short questAmount;
char diff;
short arrEasy[4] = {1, 2, 5, 10}, secondVar, ans, studAns;
void questProc() {
start:
cout << "How hard do you want the questtions to be?" << endl;
cout << "(The harder you choose, the larger the numbers you'll have to calculate)" << endl;
cout << "1) EASY" << endl;
cout << "2) MEDIUM" << endl;
cout << "3) HARD" << endl;
cout << "4) CALCULATOR MODE LOL" << endl << "~> ";
cin >> diff;
switch (diff) {
case '1':
system("cls");
cout << "EASY MODE ACTIVATED" << endl;
break;
case '2':
system("cls");
cout << "MEDIUM MODE ACTIVATED" << endl;
break;
case '3':
system("cls");
cout << "HARD MODE ACTIVATED" << endl;
break;
case '4':
system("cls");
cout << "CALCULATOR MODE ACTIVATED" << endl;
break;
default:
system("cls");
cout << "INPUTED VAL IS EITHER NOT AN INT OR ISN'T IN THE LIST"; //checks only the starting int ignores the rest...
sleep_for(0.5s); cout << "."; sleep_for(0.5s); cout << "."; sleep_for(0.5s); cout << "."; sleep_for(0.5s);
break;
if (diff != 1 && diff != 2 && diff != 3 && diff != 4) { goto start; }
}
// The following creates the question according to the set difficulty.
srand(time(NULL)); // Initializing random seed.
switch (diff) {
case 1: // Easy Mode:
system("cls");
random_shuffle(&arrEasy[0], &arrEasy[4]); // For first var.
secondVar = rand() % 10 + 1; // Rand number from 1 to 10 (for second var).
ans = arrEasy[0] * secondVar;
cout << arrEasy[0] << " * " << secondVar << " = ?" << endl << "~> ";
cin >> studAns;
break;
default:
break;
}
// The following checks if ans is correct.
if (studAns == ans) {
cout << "WELL DONE!";
}
else {
cout << "WRONG, CORRECT ANSWER WAS:" << ans;
}
}
};
I wanted it to continue on to actually calculate the question and to then check if I was right or not...
here's what I got instead:
How hard do you want the questtions to be?
(The harder you choose, the larger the numbers you'll have to calculate)
1) EASY
2) MEDIUM
3) HARD
4) CALCULATOR MODE LOL
~> 1
and then:
EASY MODE ACTIVATED
WELL DONE!
that's all it says, despite all the other things its also supposed to do...
ps. tell me if you need any more info.
Because of type mismatch!
you defined "diff" as a char and use it as such in your switch statement. However, in your second switch statement, you remove the quotes and use it as a number. That causes a char to int conversion according to the ascii table.
Look at the decimal field, the number 1 as an int corresponds to a non-printable character that you will rarely see in real life. The character '1' corresponds to 49.
Solution:
switch(diff){
case '1': //notice the quotations
//rest of code
break;
}
for this line
if (diff != 1 && diff != 2 && diff != 3 && diff != 4) { goto start; }
you mean
if (diff != '1' && diff != '2' && diff != '3' && diff != '4') { goto start; }
given that diff is a typed in char not an int
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm a beginner in programming and I am currently trying to code things myself and I encountered a question that tells me to let a user choose from number 1-12 and it will display the month it represents (ex. 1=January) using while and switch loops. I'm now so brain dead need help.
edit: it loops if I entered a wrong input like putting a or 99.
#include <iostream>
using namespace std;
int main()
{
int months = 0;
cout << "Enter a number from 1-12 (or Q to quit): " << endl;
cin >> months;
while (months != 'Q')
{
switch (months){
case 1:
cout << "January" << endl;
break;
case 2:
cout << "February"<< endl;
break;
case 3:
cout << "March" << endl;
break;
case 4:
cout << "April" << endl;
break;
case 5:
cout << "May" << endl;
break;
case 6:
cout << "June" << endl;
break;
case 7:
cout << "July" << endl;
break;
case 8:
cout << "August" << endl;
break;
case 9:
cout << "September" << endl;
break;
case 10:
cout << "October" << endl;
break;
case 11:
cout << "November" << endl;
break;
case 12:
cout << "December" << endl;
break;
default:
{
cout <<"You've entered an invalid response. Please only select from numbers 1- 12.\n";
break;
}
}
}
//I hve no idea what to do here
return 0;
}
Two issues in your code:
First you read user input once outside of the loop. When the loop is executed once then it is executed forever, because the condition never changes. Move reading input inside the loop.
Second, you mixed up characters, char, and integers ,int. 'Q' is a character literal, its a char. 1,2, etc are integer literals, they are ints.
char is in fact also a number type, but specifically with input and output char is treated differently, because the "numbers" are treated as representations of characters. A common encoding is ASCII.
Pop quiz: What do you have to enter to make this code print foo on the console:
#include <iostream>
using namespace std;
int main()
{
int x;
std::cin >> x;
if (x == 'Q') std::cout << "foo\n";
}
Answer: It depends. With the usual ascii encoding 'Q' == 81 so you need to enter 81 to make x equal to 'Q'.
std::cin >> x reads an integer. If the user enters Q then reading an int will fail. std::cin will be in an error state and x will get 0 assigned.
Decide for one: Use an int then you cannot read user input Q. Or use char then you need to compare the input against the characters '1','2' etc.
Alternatively read a std::string and parse the input to see if it is a character or a number.
You need to take the input inside the while loop not outside it !
because the while loop depends on what the user will write
so you just need to correct it to this form
while (months != 'Q')
{
cout << "Enter a number from 1-12 (or Q to quit): " << endl;
cin >> months;
}
Update :
if the user writes an invalid input your program will go inside an infinite loop again so you should think about how to terminate it immediately after an invalid input
The problem is that you used while (months != 'Q'), not if (months != 'Q'). The compiler will always loop the while loop since months is always not equal to Q. Also, months is an int, i.e. inputting Q (this is not int) will crash your code, so you might want to modify it. You can either change Q into an int, or use char month and compare with '1', '2' etc.
#include <iostream>
using namespace std;
int main() {
int months;
cin >> months;
while (months != 'Q') {
cout << "Enter a number from 1-12 (or Q to quit): " << endl;
switch (months){
case 1:
cout << "January" << endl;
break;
case 2:
cout << "February"<< endl;
break;
case 3:
cout << "March" << endl;
break;
//etc. (i'll shorten the code here)
default:
cout << "Your input is invalid. Please only input numbers 1-12.\n";
break;
}
}
return 0;
}
PS: Please indent your code properly. You do not want your code to be a mess.
Let's rename the variable and use a lookup table (array).
static const char * month_names[] =
{
"No Month as 0",
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
int month_index = 0;
std::cout << "Enter month number: ";
std::cin >> month_index;
if ((month_index > 0) && (month_index < 12))
{
std::cout << "Month name is: " << month_names[month_index] << "\n";
}
else
{
std::cerr << "Invalid month number\n";
}
In the case of mapping a number to a name, arrays work very well. You can also search the array for the month name and the index will be the month number.
I'm self-teaching myself here so I don't have a model answer available.
Working through program flow examples and trying to get a number guesser based on binary searching. I've got it to run and catch edge cases successfully but one objective is to have main() return the number of guesses made. I refactored the main code into a separate function to make it clearer, but I can't get the return code correct, I suspect it's to do with variable scope but can't figure it out.
#include <iostream>
using namespace std;
int guessNumber(int highest, int lowest, int lAttempts)
{
int guess = lowest + ((highest - lowest) * 0.5);
char response = 'a';
lAttempts++;
cout << "My guess is " << guess << ", am I correct?" << endl;
cout << "(y)es/too (h)igh/too (l)ow/(q)uit" << endl;
cin >> response;
while (response != 'y' && response != 'h' && response != 'l' && response != 'q')
{
cout << "I'm sorry, I didn't understand that" << endl;
cout << "(y)es/too (h)igh/too (l)ow/(q)uit" << endl;
cin >> response;
}
switch (response)
{
case 'y':
cout << "I guessed correctly after " << lAttempts << " attempts";
break;
case 'h':
highest = guess;
guessNumber(highest, lowest, lAttempts);
break;
case 'l':
lowest = guess;
guessNumber(highest, lowest, lAttempts);
break;
case 'q':
cout << "Exiting program";
break;
}
return lAttempts;
}
int main()
{
cout << "Think of a number between 1-100" << endl;
int highest = 100;
int lowest = 0;
int attempts = 0;
attempts = attempts + guessNumber(highest, lowest, attempts);
return attempts;
}
cout returns the correct number of attempts but the program (so main()) always exits with 1.
What am I missing here?
Thanks.
You're missing to update your attempt variable within your switch statements.
It should be like this.
lAttempts = guessNumber(highest, lowest, lAttempts);
So, I'm super new to C++ and am sharing a book with a friend. I'm creating a simple guessing game, where the user imagines a number, and the computer attempts to guess it. When I debug in Visual Studio, the project does make a guess, and properly prints "how did I do?". At this point, it should get user input for the 'feedback' variable. After the prompt, however, it seems as if it will only repeat everything before the 'while' statement. Does the problem concern the feedback char variable (maybe I should've just used 'cin' and integers?), or am I just missing something really obvious?
//Game that attempts to guess a number from one to twenty.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback[1];
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << endl << endl;
cout << " Waiting on you..." << endl << " ";
cin.get();
while(gamecont)
{
cout << " I'm thinking your number is " << guess << "." << endl << endl;
cout << " How did I do?" << endl << endl << " ";
cin.get(feedback, 1);
if (feedback[1] == 1) // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback[1] == 2) // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback[1] == 3) // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
Sorry if this question is stupid for whatever reason, and thanks in advance for reading.
a journey of a thousand miles begins with a single step, so here´s some aid for your first step:
using namespace std;
don´t do that. std:: is crowded with identifiers you might use too, problems are guaranteed.
char feedback[1];
You´ll never have input longer than 1, so
char feedback;
is more than appropriate. (besides: arrays are 0 based so it should have been char feedback[0]; instead of char feedback[1];)
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
std::endl flushes the buffer, no need to do that twice. Simply use '\n':
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
you´ll get the character code of the key in feedback. '1' is not equal to 1, so
if (feedback == 1)
should be
if (feedback == '1')
Thats it. There still some work remaining to do for you, e.g. the guessing strategy is poor, but that should be a start.
//Game that attempts to guess a number from one to twenty.
#include <iostream>
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback;
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
std::cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << "\n\n";
std::cout << " Waiting on you..." << "\n\n";
std::cin.get();
while(gamecont)
{
std::cout << " I'm thinking your number is " << guess << "." << "\n\n";
std::cout << " How did I do?" << "\n\n";
std::cin.ignore();
std::cin.get(feedback);
if (feedback == '1') // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback == '2') // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback == '3') // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
as recommended I've been working through the book 'Jumping into c++'. I'm currently on problem 7 of chapter 5 and although I have produced the code that appears to do what is asked of me I was hoping someone might be able to take a look and tell me if I've implemented any 'bad' practice (Ideally I don't want to be picking up bad habits already).
Secondly, it also says 'try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered'. Again, the code below produces a horizontal bar graph but I'm not convinced that if I had say 10000 entries (I guess I could verify this by adding an additional for loop) that it would scale according. How would one go about applying this? (such that it always properly scales regardless of how many entries).
I should probably point out at this point that I have not covered topics such as arrays, pointers and classes as of yet in case anyone was curious as to why I didn't just create a class called 'vote' or something.
One final thing... I don't have a 'return 0' in my code, is this a problem? I find it slightly confusing as to what exactly the point of having return 0 is. I know that it's to do with making sure your code is running properly but it seems sort of redundant?
Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int option;
int option_1 = 0;
int option_2 = 0;
int option_3 = 0;
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
while(option != 0)
{
if(option == 1)
{
option_1++;
}
else if(option ==2)
{
option_2++;
}
else if(option ==3)
{
option_3++;
}
else if(option > 3 || option < 0)
{
cout << "Not a valid entry, please enter again" << endl;
}
else if(option ==0)
{
break;
}
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
}
cout << "Option 1 (" << option_1 << "): ";
for(int i = 0; i < option_1; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 2 (" << option_2 << "): ";
for(int i = 0; i < option_2; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 3 (" << option_3 << "): ";
for(int i = 0; i < option_3; i++)
{
cout << "*";
}
}
About the return 0 in main : it's optional in C++.
About your code:
You have a ton of if / else if blocks, you should replace them with a switch. A switch statement is more compact, readable, and may be a little bit faster at runtime. It's not important at this point, but it's pretty good practice to know where to put a switch and where to use regular if.
You have one big function, it's really bad. You should break your code into small, reusable pieces. That's something called DRY (Don't repeat Yourself): if you are copy-pasting code, you're doing something wrong. For example, your sport list appears 2 times in your code, you should move it in a separate function.
You wrote cout << "" << endl;, I think you don't really understand how std::cout work. std::cout is an object representing the standard output of your program. You can use operator<< to pass values to this standard output. std::endl is one of these values you can pass, strings are, too. So you can just write cout << endl;, no need for an empty string.
Please learn how to use arrays, either raw ones or std::array. This is a pretty good example of a program which can be refactored using arrays.
Here is a more readable, cleaner version of your code:
#include <iostream>
int prompt_option()
{
int option;
while (true)
{
std::cout << "Which is your favourite sport?" << std::endl;
std::cout << "Tennis.. 1" << std::endl;
std::cout << "Football.. 2" << std::endl;
std::cout << "Cricket.. 3" << std::endl;
std::cin >> option;
if (option >= 0 && option <= 3)
return option;
else
std::cout << "Not a valid entry, please enter again" << std::endl;
}
}
void display_option(int number, int value)
{
std::cout << "Option " << number << " (" << value << "): ";
while (value--)
std::cout << '*';
std::cout << std::endl;
}
int main()
{
int option;
int values[3] = {0};
while (true)
{
option = prompt_option();
if (option)
values[option - 1]++;
else
break;
}
for (int i = 0; i < 3; i++)
display_option(i + 1, values[i]);
}
You have too much if else, it messy.
check out the code bellow, muc shorter, cleaner and efficent.
I hope it helps.
#include <iostream>
using namespace std;
int main()
{
int choice;
int soccer=0, NFL=0 ,formula1=0;
while(choice != 0){
cout<<"Please choose one of the following for the poll"<<endl;
cout<<"press 1 for soccer, press 2 for NFL, press 3 for formula 1"<<endl;
cout<<"Press 0 to exit"<<endl;
cin>>choice;
if(choice==1){
soccer++;
}
else if(choice==2){
NFL++;
}
else if(choice == 3){
formula1++;
}
else{
cout<<"Invalid entry, try again"<<endl;
}
cout<<"soccer chosen "<<soccer<<" times.";
for(int i=0; i<soccer; i++){
cout<<"*";
}
cout<<endl;
cout<<"NFL chosen "<<NFL<<" times.";
for(int j=0; j<NFL; j++){
cout<<"*";
}
cout<<endl;
cout<<"formula1 chosen "<<formula1<<" times.";
for(int c=0; c<formula1; c++){
cout<<"*";
}
cout<<endl;
}
return 0;
}
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.