In: Computer Science
Write a program that generates a random number between 1 and 50 and asks the user to guess it. As a hint, it tells the user how many divisors it has, (excluding 1 and the number itself). Each time the user makes a wrong guess, it displays "Wrong" and says if the guess was too low or too high, until the user gets it right, in which case it says "Right" and says how many trials it took to guess it. Then, the program asks the user if he or she wants to continue. If the answer is 'y' or 'Y', it generates another number between 1 and 50 and repeats the game. If not, it prints the average of all trials with one decimal place and ends.
Example:
I've picked a number between 1 and 50 that has 0 divisor(s).
Guess the number: 23
Too low!
Guess the number: 37
Too low!
Guess the number: 43
Too high!
Guess the number: 41
Right! It took you 4 trials.
Play again? [y/n]: y
I've picked a number between 1 and 50 that has 1 divisor(s).
Guess the number: 25
Too low!
Guess the number: 49
Right! It took you 2 trials.
Play again? [y/n]: y
I've picked a number between 1 and 50 that has 3 divisor(s).
Guess the number: 30
Too high!
Guess the number: 24
Right! It took you 2 trials.
Play again? [y/n]: n
You averaged 2.7 trials in 3 games.
Press any key to continue.
Im stuck with the loops and if you can explain the steps would be great. At the end I need to show the average in where the user guessed the correct number and how many games they played
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main(){
int game_count=0;
int total_trials=0;
while(true){
srand((unsigned)time(0));
int rnd=(rand() % 50) + 1;
//cout<<rnd<<endl; //it printed the getting random number
int divisor_count=0;
for(int i=2;i<rnd-1;i++){
if(rnd%i==0){
divisor_count=divisor_count+1;
}
}
cout<<"I've picked a number between 1 and 50 that has "<<divisor_count<<" divisor(s)."<<endl;
int n,n_count=1;
while(true){
cout<<"Guess the number:";
cin>>n;
total_trials=total_trials+1;
n_count=n_count+1;
if(n==rnd){
cout<<"Right! it took you "<<n_count<<" trials."<<endl;
game_count=game_count+1;
break;
}
if(n<rnd){
cout<<"Too low!"<<endl;
}else if(n>rnd){
cout<<"Too high!"<<endl;
}
}
char c;
cout<<"Play again?[y/n]:";
cin>>c;
if(c=='n'){
break;
}
}
cout<<"You average "<<(float)total_trials/game_count <<" trials in "<<game_count<<" games."<<endl;
return 0;
}
#if you have any doubt or more information needed comment below.i will respond as possible as soon..thanks...