I am trying to build a really simple first game with simulated dice rolls.
I am getting an error on line 49: if(rollResult>aiRollResult)
.
I'm sure it's just a really simple syntax error with all the if
statements but I cannot figure out how to fix it or can I not call the airoll()
function in the middle of my code like I did?
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void airoll();
int main() {
int b;
srand(time(0));
//random die roll
int rollResult = 1+(rand()%6);
switch (rollResult) //results options {
case 1: {
cout<<"Your Roll: 1"<<endl;
}
break;
case 2: {
cout<<"Your Roll: 2"<<endl;
}
break;
case 3: {
cout<<"Your Roll: 3"<<endl;
}
break;
case 4: {
cout<<"Your Roll: 4"<<endl;
}
break;
case 5: {
cout<<"Your Roll: 5"<<endl;
}
break;
case 6: {
cout<<"Your Roll: 6"<<endl;
}
break;
}
airoll();
if(rollResult>aiRollResult) {
cout<<"You win!"<<endl;
}
if (aiRollResult>rollResult) {
cout<<"You lose!"<<endl;
}
if (rollResult==aiRollResult) {
cout<<"It's a tie!"<<endl;
}
}
void airoll() {
int aiRollResult=1+(rand()%6);
cout<<"AI roll: "<<aiRollResult<<endl;
}
Your variable aiRollResult
is not defined in the scope of the main()
function. It only exists in the scope of the airoll()
function.
Change your airoll()
to
int airoll()
{
int aiRollResult=1+(rand()%6);
cout<<"AI roll: "<<aiRollResult<<endl;
return aiRollResult;
}
Notice the int
return type.
Now you can get the result of the airoll()
in the main function as follows:
int aiRollResult = airoll();
Which will call the airoll()
function and then store the result in the variable. That should solve your problem.
Learn more about functions here:
http://www.cplusplus.com/doc/tutorial/functions/