I'm not verse with posting actual code on daniweb but here goes:
//Assignment 5: Guessing game with random numbers and functions
//By Curtis Davenport 2/17/08
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <math.h>
using namespace std;
int GuessFunction (int);
int main()
{
int target, attempts, choice; // can be declared in the same line if the data types are the same
do // needed for requirement (4)
{
srand( time(NULL)); // maximum + minumum
target = rand()% 99 + 1; // range for rand() = (max - min) + min
// for range between 100 to 1 (100 - 1) + 1 = rand() % 99 + 1
// the result of rand() is stored in target
attempts = GuessFunction(target); // GuessFunction accepts the int variable target and returns attempts to main
// Tells the user whether they were sucessful or not after five or less tries
if (attempts <= 5)
{
cout << "You got it right in " << attempts << " attempts" << "!!! \n";
}
if (attempts > 5)
{
cout << "You ran out of chances. \n";
}
cout << "\n\nDo you want to play again? 1 for Yes - 2 for No: ";
cin >> choice;
system("PAUSE"); // pauses screen and prints message. I do not recommend this method in favour of cin.get();
} while(choice == 1); // end of dowhile for (4)
return 0;
}
/*The Guess function must ask the user to enter the guess value, compare it
with the target, notify the user if the guess is too high or too low, accumulate
the number of attempts, and check if the maximum number of attempts has been reached.
NOT THE MAIN!!!*/
// GuessFunction implementation
int GuessFunction(int target)
{
bool foundTarget = false;
bool endGame = false;
int guess, chancesLeft=5;
do
{
cout << "Guess a number (0-100): ";
cin >> guess;
if (guess < target)
{
cout << "Your Guess is too LOW!!! \n";
chancesLeft = chancesLeft - 1; // decrement chances left by one to represent attempt
}
if (guess > target)
{
cout << "Your Guess is too HIGH!!! \n";
chancesLeft = chancesLeft - 1; // decrement chances left by one to represent attempt
}
if (guess == target)
{
chancesLeft = chancesLeft - 1; // decrement chances left by one to represent attempt
foundTarget = true;
endGame = true;
}
if (chancesLeft == 0)
{
endGame = true;
}
} while (!endGame);
if (foundTarget)
{
return (5 - chancesLeft); // returns a value that represents the number of attempts to main
} // 5 represents the total allowed chances
else // 5 less the # of chances left equals the # of chances used
{
return 6; // any value greater that 5 would suffice. use to activate the second if function in main
}
} // end of function
It looks better when you click "Toggle Plain Text" and cut and paste it to a c++ compiler.
Last edited by knight fyre; Feb 19th, 2008 at 7:05 pm. Reason: Included c++ highlighting
Reputation Points: 11
Solved Threads: 1
Junior Poster in Training
Offline 88 posts
since Feb 2008