numberGuess.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <iostream>
  2. #include <string>
  3. #include <cstdlib>
  4. using namespace std;
  5. //number guessing program.
  6. //computer generates a random number
  7. //user guesses a number
  8. //computer responds with "high, low, or correct"
  9. //continue until user has guessed the number
  10. int main(){
  11. int turn = 0;
  12. int guess = 50;
  13. int diff = 25;
  14. bool correct = 0;
  15. string input = "";
  16. cout << "pick a number from 1 to 100" << endl;
  17. cout << "the computer will attempt to guess your number" << endl;
  18. cout << "enter \"low\", \"high\" or \"correct\"" << endl;
  19. while(!correct){
  20. turn++; // start with turn 1
  21. cout << turn << ": " << guess << endl; // present user with guess
  22. getline(cin, input); // high, low, or correct
  23. if (!input.compare("low")){ // user entered "low"
  24. guess = guess + diff; // guess higher
  25. } else if (!input.compare("high")){ // user entered "high"
  26. guess = guess - diff; // guess lower
  27. } else if(!input.compare("correct")) { // user entered "correct"
  28. correct = 1; // exit the loop
  29. } else { // invalid response
  30. cout << "please enter a valid response" << endl;
  31. turn--; // turn does not count
  32. }// end if
  33. diff = (diff / 2) + (diff % 2); // diff cannot be zero
  34. } // end while
  35. cout << guess << " is correct!" << endl;
  36. cout << "It took " << turn << " turns." << endl;
  37. return EXIT_SUCCESS;
  38. } // end main