Is this C++ Guessing Game syntactically correct? - c++

#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int min = 1;
int max = 100;
int count = 0;
int randomint = min + (rand() % (int)(max - min + 1));
bool isCorrect = true;
while(!isCorrect){
int guess = 0;
cout << "What is your guess? " << endl;
cin >> guess;
if(guess < randomint){
cout << "Too low!" << endl;
count++;
} else if (guess > randomint){
cout << "Too high!" << endl;
count++;
} else{
cout << "Correct!" << endl;
cout << "Number of Guesses: " << count << endl;
isCorrect = true;
}
}
}
New C++ Programming. I couldn't get this to compile one IDEOne because it doesn't have the input system I need to work this program. I have to submit this for a class shortly, but given that my larger disk (where all my software was stored) was corrupted last night.
I apologize for the silliness of this question.

Yes, it is syntactically correct, but not logically, due to
bool isCorrect = true;
which prevents loop from starting, it should be
bool isCorrect = false;
and works like a charm (but it would be reasonable to initialize the random number generator by for example running srand(time(NULL));)

There are two things logically wrong in your program:
The game won't run at all, since isCorrect is initially true.
The random number generator doesn't get a seed, so rand() will return the same value on every run and randomint is always the same. You should call srand( seed ) beforehand, where seed is a unsigned (for example time(0)).*
*actually, your game will still run if you don't do this, but it's easy to beat after the first try

Related

How can I stop C++ program?

I made a program that prompts the user to guess numbers (which I have programmed to produce a random number)ranging from 1-10, if the user guesses the number successfully which is the same as the random number generated it prints "congratulation", else it prompts the user to try again. but I want to stop the user from answering after a certain amount of time(like Game Over). But the prompt keeps coming, I tried using the break in my while loop but it doesn't work, I also tried using the exit function, which actually stopped the program from running but it stopped it after answering 2 times which is not what I want.
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int a,b,c,d,e,f;
// generate a random number, prompt the user for any number if the users guess is in line with the random number generated the user wins else try again
//generate a random number between 1 - 10 store it in a variable
cout << "Random Number Generator \n \n";
srand(time(0));
for(int i = 1; i == 1; i++){
a = 1+(rand() % 10);
cout << a << endl;
}
//prompt the user for numbers ranging from 1 - 10
cout << "type in a number from (1 - 10)\n";
cin >> b;
c++;
//check if the number is the same as the random number
//this checks to see if the user gets the question, else it continues running till he gets it
while(a != b){
cout << "You're incorrect!\n";
cout << "type in a number from (1 - 10)\n";
cin >> b;
while(b <= 3){
exit(3);
}
}
//print result
if(a == b){
cout << "congratulations";
}
return 0;
}
how can I make this work?
You could count the number of times the user answers and stop when it has executed for the number of times you want.
//prompt the user for numbers ranging from 1 - 10
cout << "type in a number from (1 - 10)\n";
cin >> b;
int answer_count = 1; // variable to count answers (there is already 1 answer here)
const int max_attempts = 10; // number of attempts the user has
//check if the number is the same has the random number
//this checks to see if the user gets the question, else it continues running till he gets it
while(a != b){
cout << "You're incorrect!\n";
cout << "type in a number from (1 - 10)\n";
cin >> b;
answer_count++; // count this new answer
if (answer_count >= max_attempts){ // check if the count reached the "certain amount of time"
break; // exit from this loop
}
}
Alternatively, you could also give the user a certain amount of time to guess. For example, 10 seconds. This can easily be achieved using the C++ chrono library:
#include <chrono>
#include <iostream>
#include <random>
int main(int argc, char **argv)
{
const int max_time = 10; // seconds
const int min_secret = 1;
const int max_secret = 10;
// This generates a random number between min_secret and max_secret using the STL random library
std::random_device r;
std::default_random_engine e(r());
std::uniform_int_distribution<int> uniform_dist(min_secret, max_secret);
int secret = uniform_dist(e);
auto start = std::chrono::system_clock::now();
int guess;
do {
std::cout << "Type a number from (1 - 10)\n";
std::cin >> guess;
if (guess == secret)
break;
std::cout << "Your guess is incorrect!\n";
// See if the time elapsed since the start is within max_time
auto now = std::chrono::system_clock::now();
auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(now - start);
if (elapsed_time.count() > max_time) {
std::cout << "You ran out of time.\n";
exit(0);
} else {
std::cout << "You still have " << max_time - elapsed_time.count() << " seconds left\n";
}
} while (guess != secret);
std::cout << "Your guess was correct, congratulations!";
}
Note that the time check is only performed after the user tried to guess, so if the time limit is 10 seconds and the user waits 30 to type, it will still allow. To kill the program entirely with a timer in C++, you could use the thread library to spawn a second thread that handles the elapsed time, or even use an interruption based scheme (see https://stackoverflow.com/a/4001261/15284149 for an example of timer).
Also, note that the user input is not sanitized, and if the user writes anything other than a number your program has undefined behavior.
You need to fix up several things in your code:
The variable c is kept uninitialized and incremented later to use nowhere. Remove this. Note that d, e, f are unused as well.
In the loop:
for(int i = 1; i == 1; i++) {
a = 1 + (rand() % 10);
cout << a << endl;
}
You have told the compiler to iterate until i == 1, increment it by one, it is only done once – and that you might not want to do but i < 10.
Also, You are not using an array to store those 10 random numbers, but the last one. You need to make an array of 10 rooms and assign it to each of them:
int a[10];
// Since the array index begins at zero
for (int i = 0; i < 10; i++) {
a[i] = (rand() % 10) + 1;
cout << a[i] << endl;
}
After the successful assignment, it's time to introduce a randomly chosen index as the right answer (it should be put before the while loop):
// To choose the random index
int shuffle = a[rand() % 10];
Also, replace the congratulating statement:
// It was a == b previously
if (shuffle == b)
cout << "congratulations";
Lastly, to quit after three incorrect attempts, replace the while loop:
int count = 0;
while (shuffle != b) {
count++;
cout << "You're incorrect!\n";
cout << "type in a number from (1 - 10)\n";
cin >> b;
if (count == 2) {
cout << "Game Over" << endl;
exit(0);
}
}

C++ - Nothing is displayed in console, no errors displayed, -1 is returned

I've recently (very, very recently) have gotten into programming in C++. I'm writing a program to find the highest prime number below prime. However, when I execute the code, nothing is displayed, and in the console it says this:
Process returned -1 (0xFFFFFFFF) execution time : 0.409 s
Press ENTER to continue.
I've tried some debugging, and I've figured out the problematic section is lines 17-19 (the if statement), but I can't figure out what I'm doing wrong.
C++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//cout << "maybe here?";
int prime = 1000;
//cout << "here";
while(true){
//cout << "here2";
int testr = ceil(sqrt(prime));
cout << testr;
bool isprime = true;
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
isprime = false;
}
}
if(isprime){
break;
}else{
prime--;
}
}
cout << prime;
}
Any and all help is appreciated! Thanks!
Additional Info:
I'm using Code::Blocks on Mac OSX 64 bit. I'm used to programming in Java, so it may just be a C++ thing I'm unaware of.
Quite a few issues.
1) The answer to your question "find the lowest prime number below prime" is 2, no programming required.
2) Assuming you want to find the greatest prime number below prime, you should test all numbers from prime - 1, downwards.
3) The very first iteration of your loop:
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
will cause an exception: division by 0.
The reason is that you are trying to divide by 0 in your for loop you should begin with 2. Take a look at this one, it's optimal I guess.
bool isPrime(int n) {
if(n<2)
return false;
for(int i=2;i*i<=n;i++)
if(n%i==0)
return false;
return true;
}

Random number generator for C++ popping up with an error?

I am having trouble with my number generator. Syntax wise, everything is working properly. I mainly wanted to use functions to see if they would work properly. When I run the program, a message pops up and says that my variable "guess" is not initialized. Can anyone give insight as to why this may be happening?
Also note that even though I didn't include my libraries in the code below, they are present in the actual program itself.
using namespace std;
int game();
string playAgain();
int main(){
game();
playAgain();
return 0;
}
int game(){
int guess;
int guessesTaken = 0;
int number = rand() % 10 + 1;
int count = 0;
cout << "I am thinking of a number between 1 and 10, can you guess it? " << endl;
while (guessesTaken < count){
cout << "Take a guess: " << endl;
cin >> guess;
if (guess > number)
cout << "Too High. Try again!" << endl;
if (guess < number)
cout << "Too Low! Try again!" << endl;
if (guess == number)
break;
}count++;
if (guess == number)
cout << "Congratulations!" << endl;
return 0;
}
string playAgain(){
string play;
cout << "Want to play again?: " << endl;
if (play == "y" || "Y")
main();
else
cout << "Thanks for playin" << endl;
return 0;
}
It happens because you did not initialise guess, precisely as the warning says.
Sure, if you assume that the cin >> guess operation will always succeed, then initialisation becomes largely irrelevant as the variable will take on a deterministic value.
But:
the compiler does not know this when it warns you, and
you have no error checking on your cin >> guess operation; not only can you not assume that it will always succeed, but your program has no clue whether it actually did.
Furthermore, the entire loop may not be executed at all if your other variables have the right values, so the compiler is completely right in its observation.
Initialise your variables and put error checking around your stream operations.
Furthermore, that count++ should obviously be in the loop body, and your loop otherwise needs refactoring in general because it begins with the 0 < 0 case. You should think hard about what you intend the semantics of your program to be.

Why are my if statements not working consistently?

I'm making a coin toss program for my c++ class and we are required to make a function that flips a coin and prints out if it is heads or tails, and print 10 per line. When I ran the program though the if statements I used to detect if the coin was heads or tails weren't enough to pick from the two.
#include <iostream>
#include <ctime>
using namespace std;
void coinToss(int times);
int main()
{
srand(time(0));
int times;
cout << "How many times would you like to toss the coin?" << endl;
cin >> times;
coinToss(times);
return 0;
}
void coinToss(int times)
{
int toss = 0, count = 0;
for(int i = 0; i < times;i++)
{
toss = rand()%2;
if(toss == 1)//Detects if coin is heads.
{
cout << "H";
}
if(toss == 0)//Detects if coin is tails.
{
cout << "T";
}
else //I had to include this for the program to run, further explanation below the code.
{
cout << "Ya done goofed.";
}
count++; //Counts to ten
if(count == 10) //Skips to the next line if the coin has been tossed ten times.
{
cout << endl;
count = 0;
}
}
}
At one point I replaced the heads or tails with "cout << toss;" and the only numbers returned were 1 and 0. I don't understand how if I'm getting only the two numbers I'm checking for some of them aren't being caught by my if statements.
To complete the assignment I've changed the second if statement into an else statement and everything seems peachy, but I'd really like to understand what's going on here.
What happens with your code is:
Is the result 1 ? Then print H. Keep going. Is the result 0 ? Then print T. Else, if it's not 0, print "Ya done goofed.".
You need to keep your if statements linked together:
if (toss == 1) {
cout << "H";
} else if (toss == 0) {
cout << "T";
} else {
cout << "Ya done goofed.";
}
You won't fall in the else case anymore and will be able to remove it.
As a sidenote, regarding your overall program structure: your coinToss function shouldn't do everything. Your code should be more splitted: a function which returns H or T, a function which calls this function X times as requested by the user and formatting the output would be a good start.
Another small note: your count variable, allowing you to add a new line every 10 flips, could be removed. i % 10 will give you the same result: every ten increments, i % 10 would be equal to 0.
You're probably printing the output properly, then terminating without writing a newline on the last line, and your shell prompts clearing back to the left margin and overwriting your output (clearing the rest of the line to boot). If you have less than 10 tosses, your only line of output may appear lost, otherwise it'll be the last line.
Try adding an extra std::cout << '\n'; before main returns.
(Separately, you can say std::cout << "HT"[rand() % 2];, or std::cout << (rand() % 2 ? 'H' : 'T'); and do away with the ifs, but it's no big deal... whatever's clearest for you at this stage)
Well, rand()%2 will produce only two numbers: 1 and 0, this seems to be in line with your task as a coin is a boolean number generator, isn't it? :)
Therefore this seems to do the job you are looking for:
#include <iostream>
#include <ctime>
using namespace std;
void coinToss(int times);
int main()
{
srand(time(0));
int times;
cout << "How many times would you like to toss the coin?" << endl;
cin >> times;
coinToss(times);
return 0;
}
void coinToss(int times)
{
int toss = 0, Count = 0;
for(int i = 0; i < times;i++)
{
toss = rand() % 2;
// Choose:
cout << ((toss) ? "H" : "T"); // if you want a character
// or
cout << toss; // if you want the number
Count++; //Counts to ten
if(Count == 10) //Skips to the next line if the coin has been tossed ten times.
{
cout << endl;
Count = 0;
}
}
}
if(toss == 1)//Detects if coin is heads.
{
cout << "H";
}
else if(toss == 0)//Detects if coin is tails.
{
cout << "T";
}
You need to use else-if statement. You also need not use else after the toss==0 because rand()%2 will either be 0 or 1. There is no third option.
rand() returns a pseudo-random integral number in the range between 0 and RAND_MAX. And, rand() % 2 will be 0 or 1. So, there would be:
if(toss == 1)//Detects if head
{
cout << "H";
}
else // tail
{
cout << "T";
}
I don't think there is anything wrong with this. Well not that I can see... If I add some debug then I see what I think you're expecting...
#include <iostream>
#include <ctime>
using namespace std;
void coinToss(int times);
int main() {
srand(time(0));
int times;
cout << "How many times would you like to toss the coin?" << endl;
cin >> times;
coinToss(times);
return 0;
}
void coinToss(int times) {
int toss = 0, count = 0;
for(int i = 0; i < times;i++) {
toss = rand() % 2;
cout << "Toss: " << toss << endl;
if(toss == 1)//Detects if coin is heads.
{
cout << "H (" << toss << ")" << endl;
}
if(toss == 0)//Detects if coin is tails.
{
cout << "T (" << toss << ")" << endl;
}
count++; //Counts to ten
if(count == 10) //Skips to the next line if the coin has been tossed ten times.
{
//cout << endl; count = 0;
}
}
}
And compile it
g++ coin_toss.cc
And run it
./a.out
How many times would you like to toss the coin?
4
Toss: 1
H (1)
Toss: 0
T (0)
Toss: 0
T (0)
Toss: 0
T (0)
Then this is exactly what I expect or am I missing something?
You don't need an "if else if" statement.
You can also use a switch:
switch( rand() % 2 )
{
case 0:
cout << "T";
break;
case 1:
cout << "H";
break;
default:
cout << "oops you goofed!;
}
// continue within for loop
If you "forgot" the break after case 1 you would again get the "oops you goofed!" message after each head toss.

Simple C++ input files and if statements

I wrote the code and it works except the total is wrong. It is supposed to multiply the distanceRate by the rate and add each cost to make the total, but it's not doing that. Any help would be appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
//Declare Variables
ifstream inFile;
double packageWeight;
double distance;
double totalCharge = 0;
double rate;
double distanceRate;
int customerNumber;
double shippingCharge;
int packageCount = 0;
inFile.open("shipping.txt");
if(inFile)
{
cout << "Customer Package Shipping" << endl;
cout << "Number Weight Distance" << endl;
while(!inFile.eof())
{
inFile >> customerNumber;
inFile >> packageWeight;
inFile >> distance;
if(0 < packageWeight <= 2)
rate = 1.10;
else if(2 < packageWeight <=6)
rate = 2.20;
else if(6 < packageWeight <= 10)
rate = 3.70;
else if(10 < packageWeight <=20)
rate = 4.80;
else
cout << "Invalid package weight" << endl;
if( 0 < distance <= 500)
distanceRate = 1;
else if( 500 < distance <= 1000)
distanceRate = 2;
else if(1000 < distance <= 1500)
distanceRate = 3;
else if(1500 < distance <= 2000)
distanceRate = 4;
else
cout << "Invalid distance" << endl;
packageCount += customerNumber;
shippingCharge = rate * distanceRate;
totalCharge += shippingCharge;
cout << fixed << setprecision(2) << showpoint;
cout << setw(2) << customerNumber
<< right << setw(14) << packageWeight
<< setw(13) << distance
<< endl;
} //End of while loop
cout << "\nPackage shipped : " << packageCount << endl;
cout << "Total Charge : $" << totalCharge << endl;
inFile.close();
}
else
{
cout << "Could not open file" << endl;
}
system("pause");
return 0;
}
Some issues that I see in the snippet you gave me are as follows:
As pointed out by billz in a comment, your if statements are invalid. The statement if( 0 < distance <= 500) is not doing what you expect, it evaluates from left to right, so you have 0 < distance (lets say that evaluates to true) so then you have true <= 1000 which isn't going to give the results that you think it will. This actually needs to be broken apart into two separate comparisons like distance > 0 && distance < 500.
As I noted in my comment, you're adding the customer number to the package count, this will most likely always give a wrong value for package count. If your customer numbers are 1, 2, 3, 4 then you claim the package count is 10 when it's actually only 4 (forgive me if I misunderstood the purpose of this field).
You have no default value for distanceRate but you still use it in an operation (possibly uninitialized) which will give unexpected results (as you are seeing). In your else, you should actually give it a dummy value that way you guarantee that it will always be set. You also do reset it, so if it gets set to 4, and then next distance fails the tests and enters the else, you have another calculation on the variable as 4 instead of it's default value. You should initialize any variable that you plan to use unless you have explicit reason not to give it a value at initialization, and anytime you use a variable in a loop you should reset it's value at the start of the loop.
Additional Note (EDIT)
I wouldn't recommend using system("pause"); as it does a lot more behind the scenes than you would want in a simple pause, a better approach I've seen used is:
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
cout << "Press any key to continue!";
_getch();
cout << "Finished";
return 0;
}
EDIT 2
If statments can contain a single line or a code block to execute.
Single line:
if (someValueIsTrue)
executeThisFunction();
Code block:
if (someValueIsTrue) {
executeThisFunction();
alsoThisFunction();
}
Anytime you need to execute more than one statement in an if/else/while/for/do...while/etc... you'll need a code block. I imagine (based on your explanation) that you did:
if (blah)
// ....
else
distanceRate = 0;
cout << "Invalid Distance";
And the compiler only sees that you have the distanceRate = 0 nested in the loop, the cout statement is actually not part of the else but part of the previous block of code. You need to use a code block here.
!inFile.eof() // incorrect
inFile.good() // correct
read on eof() it doesn't do what you might think it does.
if( 0 < distance <= 500) // all the if statements are incorrect
if(distance>0 && distance<=500) // correct
The way you wrote the if condition, it does not do what you think it does.