问题描述:

I can't for the life of me figure this out.

int Warrior :: attack ()

{

int hit;

srand(time(0));

if (Warrior.weapon == 6)

int hit = rand() % 5 + 1;

else if (Warrior.weapon == 7)

int hit = rand() % 7 + 4;

else if (Warrior.weapon == 8)

int hit = rand() % 7 + 9;

else if (Warrior.weapon == 9)

int hit = rand() % 7 + 14;

else if (Warrior.weapon == 10)

int hit = rand() % 7 + 19;

std::cout<< "You hit " << hit <<"!\n";

return hit;

}

I get this error: Error C2059: syntax error : '.'

(also I know I should use a switch statement instead of else if)

Thank You.

网友答案:

Warrior is the name of the class. If you are inside of a member function, you do not need to qualify data members with the name of the class. You should also declare hit before the chain of if-then-else:

int hit;
if (weapon == 6)
    hit = rand() % 5 + 1;
else if (weapon == 7)
    hit = rand() % 7 + 4;
else if (weapon == 8)
    hit = rand() % 7 + 9;
else if (weapon == 9)
    hit = rand() % 7 + 14;
else if (weapon == 10)
    hit = rand() % 7 + 19;

You would probably be better off with a switch statement, or even an array of pairs for % and + values.

int mod[] = {0,0,0,0,0,0,5,7,7,7,7};
int add[] = {0,0,0,0,0,0,1,4,9,14,19};
int hit = rand() % mod[weapon] + add[weapon];

In the arrays above, when weapon is, say, 8, the mod[weapon] is 7, and the add[weapon] is 9, matching the data from your if statement.

相关阅读:
Top