Let us consider a guessing game in which the computer picks a random two- digit number in the range from 0 to 99 and asks the user to guess the number. After each guess, the computer lets the player know how many digits of guessed numbers match the correct number. If the guessed number matches the correct number, the computer lets the player know the number of guesses the player made.
Question1. Each function should be tested as soon as it is written. To do that, write the intro- duction and write the main() function and call the intro function.
Question 2. To test the digitMatches() function, just call only that function with different inputs by giving two numbers. The function must work for any number in the range from 0 to 99.
Question 3. You test the getInt() for non-numeric input first and then the guessNumber() function for the value of the number in the correct range.
#include <iostream>
#include <string>
#include <time.h>Â
using namespace std;
int digitMatches(int computerNumber,int userGuess);
int guessNumber();
int getInt(string msg);
int main(){
//initialize random seed
srand (time(NULL));
int computerNumber = rand() % 100;
int userGuess=-1;
int numberQuesses=0;
while(computerNumber!=userGuess){
userGuess=guessNumber();
//After each guess, the computer lets the player knowÂ
//how many digits of guessed numbers match the correct number.
cout<<digitMatches(computerNumber,userGuess)<<" digits of guessed numbers match the correct number.\n";
numberQuesses++;
}
cout<<"\nCongratulations!. The guessed number matches the correct number.\n";
cout<<"The number of guesses made is "<<numberQuesses<<".\n\n";
system("pause");
return 0;
}
//The digitMatches() function, just call only that function with different inputs by giving two numbers.Â
//The function must work for any number in the range from 0 to 99.
int digitMatches(int computerNumber,int userGuess){
int digits = 0;
int divComputerNumber = (computerNumber - computerNumber % 10)/10;
int modComputerNumber = computerNumber % 10;
int divUserGuess = (userGuess - userGuess % 10)/10;
int modUserGuess = userGuess % 10;
int count = 0;
if (divUserGuess == divComputerNumber || divUserGuess == modComputerNumber ||Â
modUserGuess == divComputerNumber || modUserGuess == modComputerNumber){
digits++;
}
return digits;
}
//the guessNumber() function for the value of the number in the correct range.
int guessNumber(){
int number=-1;
while(number<0 || number>99){
number=getInt("Enter a number [0-99]: ");
}
return number;
}
//the getInt() checks for non-numeric input
int getInt(string msg){
int number=-1;
while(number==-1){
cout<<msg;
cin>>number;
if(cin.fail()){
cin.clear();
cin.ignore(1000,'\n');
number=-1;
}
}
return number;
}
Comments
Leave a comment