1. If num is positive then add 0.5.
2. Else subtract 0.5.
3. Type cast the result to int and return.
num = 1.67, (int) num + 0.5 = (int)2.17 = 2
num = -1.67, (int) num – 0.5 = -(int)2.17 = -2
Time complexity: O(1)
Space complexity: O(1)
Now try rounding for a given precision. i.e., if given precision is 2 then function should return 1.63 for 1.63322 and -1.63 for 1.6332.
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- C Program to Multiply two Floating Point Numbers
- Floating Point Operations & Associativity in C, C++ and Java
- Convert a floating point number to string in C
- How to count set bits in a floating point number in C?
- Rounding Floating Point Number To two Decimal Places in C and C++
- Write one line functions for strcat() and strcmp()
- LEX program to add line numbers to a given file
- getopt() function in C to parse command line arguments
- sizeof() for Floating Constant in C
- Write a C program that won't compile in C++
- How to write your own header file in C?
- When should we write our own copy constructor?
- When should we write our own assignment operator in C++?
- Write your own memcpy() and memmove()