| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- #include <iostream>
- #include <string>
- #include <cstdlib>
- using namespace std;
- //number guessing program.
- //computer generates a random number
- //user guesses a number
- //computer responds with "high, low, or correct"
- //continue until user has guessed the number
- int main(){
- int turn = 0;
- int guess = 50;
- int diff = 25;
- bool correct = 0;
- string input = "";
-
- cout << "pick a number from 1 to 100" << endl;
- cout << "the computer will attempt to guess your number" << endl;
- cout << "enter \"low\", \"high\" or \"correct\"" << endl;
-
- while(!correct){
-
- turn++; // start with turn 1
- cout << turn << ": " << guess << endl; // present user with guess
-
- getline(cin, input); // high, low, or correct
-
- if (!input.compare("low")){ // user entered "low"
- guess = guess + diff; // guess higher
- } else if (!input.compare("high")){ // user entered "high"
- guess = guess - diff; // guess lower
- } else if(!input.compare("correct")) { // user entered "correct"
- correct = 1; // exit the loop
- } else { // invalid response
- cout << "please enter a valid response" << endl;
- turn--; // turn does not count
- }// end if
- diff = (diff / 2) + (diff % 2); // diff cannot be zero
- } // end while
- cout << guess << " is correct!" << endl;
- cout << "It took " << turn << " turns." << endl;
- return EXIT_SUCCESS;
- } // end main
|