Home > Backend Development > C++ > body text

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

王林
Release: 2023-08-26 13:53:29
forward
1177 people have browsed it

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));
}
Copy after login

Output

Rounding of (2.48): 2
Rounding of (-5.79): -6
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template