Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set minimum and maximum values for an integer?

Tags:

c++

css

How do i add minimum and maximum values for an integer? I want an integer to never go down below zero like negative and never goes above 100

Here is the example:

int hp = 100;

std::cout << "You cast healing magic to yourself!" << std::endl;
hp += 20;
mp -= 25;

For example the health is 100 but when a healing magic is cast it became 120. The thing i want is i want it to stay as 100 no matter how many healing magic are cast upon.

like image 601
Ban Avatar asked Aug 27 '26 13:08

Ban


2 Answers

You can use std::clamp:

hp = std::clamp(hp + 20, 0, 100);
mp = std::clamp(mp - 25, 0, 100);
like image 57
Ted Lyngmo Avatar answered Aug 30 '26 01:08

Ted Lyngmo


You can use std::clamp as suggested by @TedLyngmo if you are using a compiler which supports C++ 17. If not, then you can write a simple function to manage the limits for hp and mp:

void change(int& orig, int val)
{
    int temp = orig + val;
    if (temp <= 0)
        temp = 0;
    else if (temp >= 100)
        temp = 100;
    orig = temp;
}

int main()
{
    int hp = 40, mp = 40;

    std::cout << "You cast healing magic to yourself!" << std::endl;
    
    change(hp, 50);
    change(mp, -25);

    std::cout << hp << " " << mp << std::endl;
}
like image 21
kiner_shah Avatar answered Aug 30 '26 02:08

kiner_shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!