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 say as 100 no matter how many healing magic are cast upon.
CodePudding user response:
You can use std::clamp
:
hp = std::clamp(hp 20, 0, 100);
mp = std::clamp(mp - 25, 0, 100);
CodePudding user response:
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;
}
CodePudding user response:
I believe what you are saying is whatever the healing magic is you want to display 100 or your hp the way it is. If so you can store the 20 and 25 as variables and create another var with the same value as ur original one and play around with that. Don't change the value of ur original one and so you get to display that.