Home  >  Article  >  Backend Development  >  Write a one-line C function to round floating point numbers

Write a one-line C function to round floating point numbers

王林
王林forward
2023-08-26 13:53:291123browse

Write a one-line C function to round floating point numbers

Here we will see how to write a one line C function that can round floating point numbers. In order to solve this problem, we have to follow the following steps.

  • Get the number
  • If the number is positive, add 0.5
  • Otherwise, subtract 0.5
  • Use type conversion to convert the floating point value Convert to integer

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</p><p>", my_round(2.48));
   printf("Rounding of (-5.79): %d</p><p>",my_round(-5.79));
}

Output

Rounding of (2.48): 2
Rounding of (-5.79): -6

The above is the detailed content of Write a one-line C function to round floating point numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete