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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- C Program to Multiply two Floating Point Numbers
- Problem in comparing Floating point numbers and how to compare them correctly?
- Floating Point Operations & Associativity in C, C++ and Java
- How to count set bits in a floating point number in C?
- Convert a floating point number to string 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
- C program to print odd line contents of a File followed by even line content
- 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++
- Write your own memcpy() and memmove()
- When should we write our own copy constructor?
- How to write your own header file in C?
- When should we write our own assignment operator in C++?
- C program to write an image in PGM format
- Read/Write structure to a file in C
- Write a C macro PRINT(x) which prints x