Jan 21, 2012 at 9:04am UTC
I don't know what "the equal variable" is, but you are already checking of guess == random
. If guess == random
, then you enter case random:
.
I see you have a variable called try
. Have you noticed the colour of try
? This means it's a reserved word. Just like if switch return default case while for do goto try throw class struct int float double char unsigned static extern etc
. You need to use another word because try has a specific meaning when compiled.
Last edited on Jan 21, 2012 at 9:05am UTC
Jan 21, 2012 at 10:23am UTC
ah I see, the problem now.
1. Remove the line that defines random
(which is not in the code above).
2. Replace line 6 with const int random = rand()%10+1;
.
This makes random
read-only (after definition). This is required for a case statement.
Jan 21, 2012 at 11:30am UTC
Did it compile? If if compiled and nothing happened when you ran the program, then guess != gnum.
Jan 21, 2012 at 11:38am UTC
Compiler:
case label does not reduce to an integer constant
Jan 21, 2012 at 3:36pm UTC
The compiler needs to know the number of a switch statement before it's compiled, otherwise you could have 2 cases that are the same.
This is not the same as a constant integral since it won't be generated until runtime since you are calling "rand()";
const int gnum = rand()%10+1;
Why not use a loop?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
srand(time(0));
int value = rand();
int tries = 10;
do {
int guess;
cout << "Enter value: "
cin >> guess;
} while ( guess != value && --tries );
if (tries > 0) cout << "You're right!\n" ;
else cout << "too bad.\n" ;
You could even use a for loop, which would make a bit more sense with the tries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int value = rand();
for (int i = 10; i > 0; i--)
{
int guess;
cout << "tries: " << i << endl;
cout << "enter value: " ;
cin >> guess;
if ( guess == value ){
cout << "party!\n" ;
break ;
}
else {
cout << " try again\n" ;
}
}
Last edited on Jan 21, 2012 at 3:43pm UTC