samedi 17 septembre 2016

if statement being ignored in a basic c++ number guessing program

I am new to c++ coming from Java. My assignment is simple, make a program that generates a random number 0-20, has the user guess up to 10 times, count their attempts and then output their guesses if they win or lose. However no matter how I try to increment my tried variable it stays at 0

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int getRandomNumber()
{
    srand(time(NULL)); //seed for our RNG
    return rand() % 21; //returns anything 0-20
}

int main()
{
    int toGuess = getRandomNumber();
    cout << toGuess << "\n"; //debug
    int tried = 0; // times tried
    int won = 0;
    int guessed = -1;
    while (tried <= 10 || won != 0) 
    {
        cout << "Guess a number 0 - 20 : ";
        tried++;
        cin >> guessed;
        if (guessed != toGuess)
        {
            cout << "You did not select the correct number, try again \n";
            tried = tried + 1;
        }

        else if (guessed == toGuess)
        {
            cout << "It took you " << tried << " times to guess the right number!";
            won = 1;
        }


    }
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire