Created
January 24, 2013 19:01
-
-
Save kdmkdmkdm/4626499 to your computer and use it in GitHub Desktop.
generatingrandomguesses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // guessmynumberreversed.cpp : Defines the entry point for the console application. | |
| // | |
| #include "stdafx.h" | |
| #include <iostream> | |
| #include <cstdlib> | |
| #include <ctime> | |
| using namespace std; | |
| int main() | |
| { | |
| srand(static_cast<unsigned int>(time(0))); | |
| int number; | |
| cout << "Choose a number for the computer to guess: "; | |
| cin >> number; | |
| while (number < 0) | |
| { | |
| cout << "A negative number cannot be chosen for this game. Choose a positive: "; | |
| cin >> number; | |
| } | |
| int randomNumber = rand(); | |
| int lastguess = RAND_MAX; | |
| int guess = randomNumber % lastguess; // Guess a number | |
| cout << "The computer guesses " << guess << ". "; | |
| // count the guesses | |
| int guesses = 1; | |
| while (guess != number) | |
| { | |
| if (guess < number) | |
| { | |
| cout << "It guessed too low..." << endl; | |
| randomNumber = rand(); | |
| guess = randomNumber; | |
| cout << "The computer guesses " << guess << ". "; | |
| } | |
| else if (guess > number) | |
| { | |
| cout << "It guessed too high..." << endl; | |
| randomNumber = rand(); | |
| lastguess = guess; // Change lastguess so that the next guess is, at most, the value of the last guess | |
| guess = randomNumber % lastguess; | |
| cout << "The computer guesses " << guess << ". "; | |
| } | |
| ++guesses; | |
| } | |
| if (guess == number) | |
| { | |
| cout << "It guessed correctly! And it took " << guesses << " guesses!" << endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment