How can I increment a variable without exceeding a maximum value?

前端 未结 14 1742
别跟我提以往
别跟我提以往 2021-01-30 12:03

I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at

14条回答
  •  半阙折子戏
    2021-01-30 12:45

    just add 15 to the health, so:

    health += 15;
    if(health > 100){
        health = 100;
    }
    

    However, as bland has noted, sometimes with multi-threading (multiple blocks of code executing at once) having the health go over 100 at any point can cause problems, and changing the health property multiple times can also be bad. In that case, you could do this, as mentioned in other answers.

    if(health + 15 > 100) {
        health = 100;
    } else {
        health += 15;
    }
    

提交回复
热议问题