如何在不超过最大值的情况下增加变量? [英] How can I increment a variable without exceeding a maximum value?

查看:84
本文介绍了如何在不超过最大值的情况下增加变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为学校开发一个简单的视频游戏程序,我已经创建了一种方法,如果调用该方法,玩家将获得15个健康点。我必须保持最高100的健康状态,并且我现在有限的编程能力,我正在做这样的事情。

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 a max of 100 and with my limited programming ability at this point I am doing something like this.

public void getHealed(){
    if(health <= 85)
        health += 15;
    else if(health == 86)
        health += 14;
    else if(health == 87)
    health += 13; 
}// this would continue so that I would never go over 100

我理解我的关于语法并不完美,但我的问题是,这可能是一个更好的方法,因为我还必须对损伤点做类似的事情,而不是低于0。

I understand my syntax about isn't perfect but my question is, what may be a better way to do it, because I also have to do a similar thing with the damage points and not go below 0.

这称为饱和算术

推荐答案

我会这样做。它基本上需要在100(最大生命值)和15点额外健康之间的最小值。它确保用户的健康状况不超过100。

I would just do this. It basically takes the minimum between 100 (the max health) and what the health would be with 15 extra points. It ensures that the user's health does not exceed 100.

public void getHealed() {
    health = Math.min(health + 15, 100);
}

为了确保生命值不低于零,你可以使用类似的功能: Math.max

To ensure that hitpoints do not drop below zero, you can use a similar function: Math.max.

public void takeDamage(int damage) {
    if(damage > 0) {
        health = Math.max(health - damage, 0);
    }
}

这篇关于如何在不超过最大值的情况下增加变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆