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

前端 未结 14 1738
别跟我提以往
别跟我提以往 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:54

    If you want to be cheeky and fit your code on one line, you could use a ternary operator:

    health += (health <= 85) ? 15 : (100 - health);
    

    Note that some people will frown upon this syntax due to (arguably) bad readability!

提交回复
热议问题