← Back

16. Rounding Floating-Point Numbers

Easy

πŸ“ Problem

Display the given floating point value to its nearest integer value.

Input Format:
Accept a floating point value as input.
Output Format:
Print the nearest integer value
Constraints:
3.4E-4932 <= inp <= 1.1E+4932
πŸŽ“ Complete Guide to Rounding in C++

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!

1️⃣ All Standard Rounding Functions

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

2️⃣ Understanding 0.5 Behavior

round() - Rounds AWAY from zero
round(2.5) β†’ 3
round(-2.5) β†’ -3
floor() - Always toward -∞
floor(2.5) β†’ 2
floor(-2.5) β†’ -3
ceil() - Always toward +∞
ceil(2.5) β†’ 3
ceil(-2.5) β†’ -2
trunc() - Chops decimals (toward zero)
trunc(2.5) β†’ 2
trunc(-2.5) β†’ -2

3️⃣ Beginner Mistakes to Avoid

⚠️ Common Pitfalls
  • Casting without rounding: (int)3.7 gives 3, not 4
  • floor/ceil confusion: floor(-2.7) is -3, not -2!
  • Floating-point precision: 2.999999 may not equal 3.0 exactly
  • 0.5 rounding: round() goes away from zero, not always up

4️⃣ Rounding to Decimal Places

Want to round to 2 decimal places? Multiply, round, divide!

double x = 2.5678;
double rounded = round(x * 100.0) / 100.0;
// Result: 2.57

5️⃣ Manual Rounding (Without <cmath>)

If you can't use <cmath>, implement it yourself:

int nearest = (num >= 0) ? (int)(num + 0.5) 
                         : (int)(num - 0.5);

πŸ“Š Quick Reference Table

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!

Examples

Sample Input 1:
Input:
15.9
Sample Output 1:
Output:
16
Sample Input 2:
Input:
159.357
Sample Output 2:
Output:
159
Solution.cpp
#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;
}