Oki
Oki

Reputation: 41

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?

Upvotes: 3

Views: 4148

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106096

One way is std::max...

std::cout << "Health: " << std::max(Player.HP, 0) << '\n';

Upvotes: 8

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Extract your behavior with a getter function:

class Player {
int HP;

public:
    int getHP() const { return HP > 0 ? HP : 0; }
}

Upvotes: 7

VLL
VLL

Reputation: 10155

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.

Upvotes: 7

Related Questions