Display the given floating point value to its nearest integer value.
This problem opens a whole new world of rounding techniques!
At first, this looks simpleβjust round a number. But there are actually 8 different rounding functions in C++, each with unique behavior, especially with negative numbers!
Function | Behavior | x = 2.7 | x = -2.7 | Return Type |
---|---|---|---|---|
round(x) |
Nearest integer (0.5 β away from zero) | 3 | -3 | double |
lround(x) |
Same as round() | 3 | -3 | long |
llround(x) |
Same as round() | 3 | -3 | long long |
floor(x) |
Down toward -β | 2 | -3 | double |
ceil(x) |
Up toward +β | 3 | -2 | double |
trunc(x) |
Toward zero (chop decimals) | 2 | -2 | double |
nearbyint(x) |
Nearest (current rounding mode) | 3 | -3 | double |
rint(x) |
Like nearbyint(), may raise exceptions | 3 | -3 | double |
round(2.5)
β 3round(-2.5)
β -3floor(2.5)
β 2floor(-2.5)
β -3ceil(2.5)
β 3ceil(-2.5)
β -2trunc(2.5)
β 2trunc(-2.5)
β -2(int)3.7
gives 3
, not 4
floor(-2.7)
is -3
, not -2
!2.999999
may not equal 3.0
exactlyround()
goes away from zero, not always upWant to round to 2 decimal places? Multiply, round, divide!
double x = 2.5678;
double rounded = round(x * 100.0) / 100.0;
// Result: 2.57
If you can't use <cmath>
, implement it yourself:
int nearest = (num >= 0) ? (int)(num + 0.5)
: (int)(num - 0.5);
Goal | Function / Method |
---|---|
Nearest integer | round(x) |
Round down | floor(x) |
Round up | ceil(x) |
Remove decimals | trunc(x) or (int)x |
Round to n decimals | round(x * 10^n) / 10^n |
β
For this problem, use round()
for nearest integer!
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long double f;
cin >> f;
// round() returns the nearest integer
// If decimal is 0.5, rounds AWAY from zero
// Examples: round(2.7) = 3, round(-2.7) = -3
cout << round(f);
return 0;
}