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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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?
- Write one line functions for strcat() and strcmp()
- How to count set bits in a floating point number in C?
- Convert a floating point number to string in C
- Floating Point Operations & Associativity in C, C++ and Java
- Rounding Floating Point Number To two Decimal Places in C and C++
- C program to print odd line contents of a File followed by even line content
- sizeof() for Floating Constant in C
- Swap two variables in one line
- LEX program to add line numbers to a given file
- getopt() function in C to parse command line arguments
- Write a C program to print "Geeks for Geeks" without using a semicolon
- Write a C macro PRINT(x) which prints x
- When should we write our own copy constructor?
- Does C++ compiler create default constructor when we write our own?
- When should we write our own assignment operator in C++?
- Write a C program that does not terminate when Ctrl+C is pressed
- fopen() for an existing file in write mode