Write a one line C function to round floating point numbers

CServer Side ProgrammingProgramming

Here we will see how to write one-line C function, that can round floating point numbers. To solve this problem, we have to follow these steps.

  • Take the number
  • if the number is positive, then add 0.5
  • Otherwise, subtract 0.5
  • Convert the floating point value to an integer using typecasting

Example

#include <stdio.h>
   int my_round(float number) {
   return (int) (number < 0 ? number - 0.5 : number + 0.5);
}
int main () {
   printf("Rounding of (2.48): %d\n", my_round(2.48));
   printf("Rounding of (-5.79): %d\n",my_round(-5.79));
}

Output

Rounding of (2.48): 2
Rounding of (-5.79): -6
raja
Published on 02-May-2019 07:36:09
Advertisements