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
|
// Brent Sonnen
// 01-23-2012
// Number guessing game
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int random()
{
int randomNumber = rand()%1000+1;
return (randomNumber);
}
void start(int randomNumber) {
int guess;
int counter=0;
cout << "Welcome to the number guessing game!" << endl;
while(true){
cout << "Please input a number between 1 and 1000" << endl;
cin >> guess;
if (guess == randomNumber) {
cout << "You have guessed the number!" << endl;
break;
} else {
if (guess > randomNumber) {
cout << "Your guess of " << guess << " is too high" << endl;
counter++;
} else {
cout << "Your guess of " << guess << " is too low." << endl;
counter++;
}
}
}
}
int main()
{
start(random());
}
|
1. first, since start wont return any value it must be a void method... void start()
2. you must declare the variables to pass as parameters in a function... void start ( int randomNumber )
3. about the expected , error, that is because you missed a { next to the function declaration: void start (int randomNumber){
4. there was an error about counter variable not existing... i created it and initialized it on 0 int counter=0;
5. Go to the main function... there you can't start the function because it won't return any value, that's why you need it to be void... and you need to pass the function the number the computer randomly calculated... you can either, do it by integrating the random function as a parameter in the start function (as i did), or you can do this.
int number= random();
start (number);
and also, inside your guessing method, after the user types his guess, whether he guesses the number or not, the program will end, because you don't loop the process... I added a while(true) to the whole asking process so it will run without ending unless you guessed the number, when the break; i added will end the cycle...
if you are trying to get the user to guess the number with limited attempts, you can add also an if(counter==attempts){
cout<<"\n Your attempts are over";
break;
}
I'd recommed reading how functions work, since int,double,etc ones need you to catch their return in a variable, and voids do not...
Sorry for my english, it sucks lol...