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.
You can use std::clamp:
hp = std::clamp(hp + 20, 0, 100);
mp = std::clamp(mp - 25, 0, 100);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With