1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include <iostream>
#include <cmath>
using namespace std;
//Write the Function prototype
int distanceToClosest (const int solutions[], int SIZE, int guess);
int main()
{
//Be sure to initialize the array and the variables.
const int SIZE = 5;
const int solutions[SIZE] = { 31, 111, 351, 752, 999 };
int distance = 0, secondDistance = 0, guess = 0, nextGuess = 0;
//Describe the game to the user and ask for their input
cout << "\t\t---The Guessing Game---" << endl;
cout << "Welcome to the Number Guessing Game!" << endl;
cout << "Can you guess the correct number? Give it a try!" << endl;
cin >> guess;
//Be sure the number is in the correct range (1-1000)
while (guess < 0 || guess > 1000)
{
cout << "Error! Please pick a number between 1-1000!" << endl;
cin >> guess;
}
//Figure out if user has guessed the correct number. If so, close program.
for (int i = 0; i < SIZE; i++)
{
if (guess == solutions[i])
{
cout << "You were correct on your first try! Congratulations!" << endl;
return 0;
}
else if (guess != solutions [i])
{
cout << "Sorry! that is incorrect!" << endl;
}
//Start of the do-while loop that will close if the number is picked.
do
{
//Have the user make another guess
cout << "Please pick a number!" << endl;
cin >> nextGuess;
//Make sure the next number is in range
while (nextGuess < 0 || nextGuess > 1000)
{
cout << "Error! Please pick a number between 1-1000!" << endl;
cin >> nextGuess;
}
//Figure out if guess is closer (warmer) or further away (colder)
//from the previous guess
distance = distanceToClosest(solutions,SIZE,guess);
secondDistance = distanceToClosest(solutions, SIZE, nextGuess);
if (nextGuess == solutions[i])
{ cout << "Correct!" << endl;
return 0;
}
else if (distance == secondDistance)
{ cout << "Your guess is the same distance away as your last!" << endl;
}
else if (distance > secondDistance)
{ cout << "Getting Colder!" << endl;
}
else if (distance < secondDistance)
{ cout << "Getting Warmer" << endl;
}
//You must change the value of lastGuess before re-running loop
nextGuess = guess;
}
//end loop if correct
while (distance != 0);
}
return 0;
}
//Determine the distance of the guess to closest solutions
int distanceToClosest (const int solutions[], int SIZE, int guess)
{
int diff[SIZE];
for (int i = 0; i < SIZE; i++)
{
diff[i] = abs(solutions[i] - guess);
}
int lowest = diff[0];
for (int k = 0; k < SIZE; k++)
{
if (lowest > diff[k])
{
lowest = diff[k];
}
}
return lowest;
}
|