# include <iostream>
using namespace std;
int main(){
/*declaring boolean that states if player's health is less than one
they are dead/true */
int playerHealth = 10;
bool isPlayerDead=playerHealth < 1;
//kills player
playerHealth = playerHealth - 10;
//if statement to prove that player died.
if(isPlayerDead){
cout << "You died" << endl;
cout << isPlayerDead << endl;
cout << playerHealth << endl;
}
else{
cout << "You are alive" << endl;
cout << isPlayerDead << endl;
cout << playerHealth << endl;
}
return 0;
}
如果玩家受到10点伤害,并且他们的生命值现在为0,则他们的生命值小于1.这不会使布尔值为真,为什么不是?
答案 0 :(得分:3)
您在创建时已将isPlayerDead
初始化为false
。
然后修改playerHealth
以便玩家死亡 - 但之后你不会更新isPlayerDead
,因此它仍然包含false。
如果您每次使用它都需要更新,请考虑使用功能:
bool isPlayerDead() { return playerHealth < 1; }
int main() {
// ...
if (isPlayerDead())
//...