Oki Oki - 1 month ago 8
C++ Question

How to print a negative number as 0?

For class I've made a turn based fighting game that keeps track of the user's health with:

Player.HP = 100;
(inside a structure)

It's printed with
cout << "Health: " << Player.HP << endl;


The do while loop is exited once their health or the computer opponents health is equal or less than 0

} while ((Player.HP >= 0) && (com.HP >= 0));


If for instance the health is equal to -14 is there a way to have it printed as 0 in a cleaner way than using an if statement?

Answer

You can write the if statement with inline if:

cout << "Health: " << (Player.HP >= 0 ? Player.HP : 0) << endl;

This prints Player.HP if it is greater or equal to zero, and prints zero otherwise.

Comments