C++ examples for Data Type:Random
Randomly generate numbers between 1 and 1000 for user to guess.
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; void guessGame(); // function prototype bool isCorrect( int, int ); // function prototype int main()//from w ww . j av a 2 s . com { srand( time( 0 ) ); // seed random number generator guessGame(); return 0; // indicate successful termination } // guessGame generates numbers between 1 and 1000 and checks user's guess void guessGame() { int answer; int guess; // user's guess char response; // 'y' or 'n' response to continue game do { answer = 1 + rand() % 1000; cout << "Can you guess my number between 1 and 1000?\n" << "Please type your first guess." << endl << "? "; cin >> guess; while ( !isCorrect( guess, answer ) ) cin >> guess; cout << "\nYou guessed the number!\n" << "Would you like to play again (y or n)? "; cin >> response; cout << endl; } while ( response == 'y' ); } bool isCorrect( int g, int a ) { // guess is correct if ( g == a ) return true; // guess is incorrect; display hint if ( g < a ) cout << "Too low. Try again.\n? "; else cout << "Too high. Try again.\n? "; return false; }