Last active
July 27, 2023 14:52
-
-
Save Niriel/1f003d8d33971a1125027104650e1db0 to your computer and use it in GitHub Desktop.
C++ bounded floats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
#include <cassert> | |
#define DEBUG_BOUNDS 1 // 1 enabled, 0 disabled. | |
class BoundedFloat { | |
private: | |
float _value; | |
public: | |
BoundedFloat(const float low, const float high, const float value): | |
_value(value){ | |
assert(low <= value && value <= high); | |
} | |
operator float() { | |
return _value; | |
} | |
}; | |
#if DEBUG_BOUNDS | |
#define HitPoint(value) BoundedFloat(0.0, 100.0, value) | |
#define Damage(value) BoundedFloat(0.0, INFINITY, value) | |
#else | |
#define HitPoint(value) float(value) | |
#define Damage(value) float(value) | |
#endif | |
int main() { | |
// Write C++ code here | |
auto hit_points = HitPoint(100.0); | |
auto damage = Damage(20.0); | |
for (int i = 0; i < 6; i++) { | |
std::cout << float(hit_points) << "\n"; | |
hit_points = HitPoint(hit_points - damage); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment