--Originally published at my programming blog
The assignment is to create a program in which you need to guess the number the computer was thinking, and if you get it wrong the program tells you if its too high or to small and when you get it right it tells the number of times it took you to get it right.
Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main (){
int x, secret,y=0;
srand(time(NULL));
secret=(rand()%100+1);
cout<< “I chose a number between 1-100, can you guess it?: “<<endl;
do {
cout<<“Write your guess:”<<endl;
cin>>x;
y=y + 1;
if(x>secret){
cout<<“Wrong! ” <<x<< ” is too high, try again.”<<endl;
} else {
if (x<secret){
cout<<“Wrong! “<<x<< ” is too low, try again.”<<endl;
}
}
}while(x!=secret);
cout<<“Congratulations you got it right!!”<<endl;
cout<<“It took you “<<y<<” times to get it right.”<<endl;
return 0;
}
- I included the libraries “cstdlib” and “ctime” so that I could use the srandom function and the time function.
- Then I named my variables (the integers “x”, “y” and “secret”)
- I wrote the function of srand and inside the parenthesis I wrote time(NULL) so that the random number is always different.
- Then I equaled the integer “secret” to the random function “rand” and put %100 +1 to specify that I want a number between 1 and a 100.
- I added the cout to ask the user for a number.
- I made a loop called do-while, this means that while a condition is true this loop will repeat, so I did it with the condition that x!=secret, so while the user doesn’t guess the secret number this will repeat itself.
- Inside the loop I added an if so if x>secret the program tells you your number is too high, and another if so if Continue reading "Guess the number"