Write a one line C function to round floating point numbers
Algorithm: roundNo(num)
1. If num is positive then add 0.5.
2. Else subtract 0.5.
3. Type cast the result to int and return.
Example:
num = 1.67, (int) num + 0.5 = (int)2.17 = 2
num = -1.67, (int) num – 0.5 = -(int)2.17 = -2
Implementation:
/* Program for rounding floating point numbers */# include<stdio.h> int roundNo(float num) { return num < 0 ? num - 0.5 : num + 0.5; } int main() { printf("%d", roundNo(-1.777)); getchar(); return 0; } |
chevron_right
filter_none
Output: -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.
Recommended Posts:
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- C Program to Multiply two Floating Point Numbers
- 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++
- 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
- When should we write our own copy constructor?
- When should we write our own assignment operator in C++?
- Write your own memcpy() and memmove()
- How to write your own header file in C?
- Write a C program that won't compile in C++



