In C, the round()
function is used to round a floating-point number to the nearest integer. If the fractional part of the number is 0.5 or greater, the number is rounded up; otherwise, it is rounded down. This function is part of the math.h
library.
Syntax:
#include <math.h>
double round(double x);
Parameters:
x
: The floating-point number you want to round.
Return Value:
- The function returns the nearest integer value as a
double
. If the input is already an integer, it returns the same value. - If
x
is exactly halfway between two integers, it rounds away from zero (i.e., it rounds up for positive numbers and rounds down for negative numbers).
Example:
#include <stdio.h>
#include <math.h>
int main() {
double num1 = 3.6;
double num2 = 3.2;
double num3 = -3.5;
printf("round(3.6) = %.0f\n", round(num1));
printf("round(3.2) = %.0f\n", round(num2));
printf("round(-3.5) = %.0f\n", round(num3));
return 0;
}
Output:
round(3.6) = 4
round(3.2) = 3
round(-3.5) = -4
Notes:
- To use the
round()
function, you must include themath.h
library. - Make sure to link with the math library by using the
-lm
flag when compiling the program (e.g.,gcc program.c -lm
).
The round()
function is useful for applications where you need precise rounding to the nearest integer.