There are several ways to round floating-point numbers in C++, each with its own specific behavior. Let's explore the main approaches:
The <cmath>
library provides several useful rounding functions:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
float damage{24.7f};
// Round to nearest integer
int roundedDamage{
static_cast<int>(std::round(damage))};
// Round down (floor)
int floorDamage{
static_cast<int>(std::floor(damage))};
// Round up (ceiling)
int ceilingDamage{
static_cast<int>(std::ceil(damage))};
cout << "Original: " << damage << "\n";
cout << "Rounded: " << roundedDamage << "\n";
cout << "Floor: " << floorDamage << "\n";
cout << "Ceiling: " << ceilingDamage;
}
Original: 24.7
Rounded: 25
Floor: 24
Ceiling: 25
Sometimes you want to round to a specific number of decimal places:
#include <cmath>
#include <iostream>
using namespace std;
float roundToDecimalPlaces(
float value, int decimalPlaces
) {
double multiplier{pow(10.0f, decimalPlaces)};
return round(
value * multiplier) / multiplier;
}
int main() {
float health{95.6789f};
// Round to various decimal places
float oneDecimal{
roundToDecimalPlaces(health, 1)};
float twoDecimals{
roundToDecimalPlaces(health, 2)};
cout << "Original: " << health << "\n";
cout << "One decimal place: "
<< oneDecimal << "\n";
cout << "Two decimal places: "
<< twoDecimals;
}
Original: 95.6789
One decimal place: 95.7
Two decimal places: 95.68
Here's a more practical example showing how rounding can be used in game mechanics:
#include <cmath>
#include <iostream>
using namespace std;
float calculateDamage(
float baseDamage, float multiplier
) {
float rawDamage{baseDamage * multiplier};
// Round to nearest whole number
return round(rawDamage);
}
int main() {
float weaponDamage{10.0f};
float criticalMultiplier{1.5f};
float damage{
calculateDamage(
weaponDamage, criticalMultiplier)};
cout << "Critical hit damage: "
<< damage << "\n";
// Multiple calculations
float multipliers[]{
0.8f, 1.0f, 1.2f, 1.5f
};
cout <<
"\nDamage with different multipliers:";
for (float mult : multipliers) {
cout << "\nMultiplier " << mult << ": "
<< calculateDamage(
weaponDamage, mult);
}
}
Critical hit damage: 15
Damage with different multipliers:
Multiplier 0.8: 8
Multiplier 1: 10
Multiplier 1.2: 12
Multiplier 1.5: 15
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the different types of numbers in C++, and how we can do basic math operations on them.