While loop condition not working
-
06-07-2021 - |
Question
Hey basically i want both the player and the wolves to attack each other until one another are dead. But the while loop is infinite so obviously the condition is not met. But i cant see where i am going wrong with this if ( choice1 == 1) // if statement is used throughout the game to allow the user to interact through the game with choices.
while((Status.health != 0) && (Wolves.health != 0) )
{
int playerAttack = Status.strength + hitPoints() + Rock.attack;
cout<< "This is the player attack" << playerAttack;
Wolves.health = Wolves.health - playerAttack;
cout << "This is the wolves health" << Wolves.health;
if (Wolves.health <= 0)
{
cout << "\nThe wolves are dead\n ";
}
int wolfAttack = Wolves.attack + hitPoints();
Status.health - wolfAttack;
if(Status.health <= 0)
{
gameOver();
}// print out of object health.
}
Can anybody help ?
Solution
Well, i think the health was not exact 0 - because your condition looks only for != 0 it should be bigger than 0
while((Status.health > 0) && (Wolves.health > 0)) ...
edit: also the missing = John Dibling found first
OTHER TIPS
Compare:
Wolves.health = Wolves.health - playerAttack;
vs
Status.health - wolfAttack;
Notice any difference?
Are you sure that this is correct:
Status.health - wolfAttack;
This actually is a no-operation. Perhaps you meant:
Status.health -= wolfAttack;
in computer some of numbers cannot be represented for example 0.1, so if you calculate 1 - (0.1 * 10) its result not equal to zero. You checked only !=0 and ==0 condition. Try this:
=0 or <=0 also if your "health" variable is integer you give a error tolerance such as: =(0.5) or <=(0.5) etc...
Most likely both values are never zero. That sounds likely, because you yourself use the <=
condition.
I think your are getting negative values, I recomend to use
while((Status.health > 0) && (Wolves.health > 0) )