C library - round() function



The C library round() function can be used to calculate the floating-point into the nearest integer. This function is a part of C99 standard and defined under the header math.h.

Suppose we have a integer like 0.5 or above, the function round up to the next integer otherwise it round it down.

Syntax

Following is the syntax of the C library function round()

double round(double x);

Parameters

This function accepts only a single parameter −

  • x − This parameter is used to set the floating-point number to be rounded.

Return Value

This function return the rounded value of x. Suppose the fractional part of x is 0.5 then the function rounds away from zero.

Example 1

Following is the basic example that illustrate the usage of C library round() function.

#include <stdio.h>
#include <math.h>

int main() {
   double n1 = 8.6;
   double n2 = 6.2;
   double n3 = -31.6;
   double n4 = -32.2;
   double n5 = 32.5;
   double n6 = -12.5;

   printf("round(%.1f) = %.1f\n", n1, round(n1)); 
   printf("round(%.1f) = %.1f\n", n2, round(n2)); 
   printf("round(%.1f) = %.1f\n", n3, round(n3)); 
   printf("round(%.1f) = %.1f\n", n4, round(n4)); 
   printf("round(%.1f) = %.1f\n", n5, round(n5)); 
   printf("round(%.1f) = %.1f\n", n6, round(n6)); 

   return 0;
}

Output

The above code produces the following result −

round(8.6) = 9.0
round(6.2) = 6.0
round(-31.6) = -32.0
round(-32.2) = -32.0
round(32.5) = 33.0
round(-12.5) = -13.0

Example 2

The program represent the array of integers(positive and negative) which can be used to calculate the nearest integer using round() function.

#include <stdio.h>
#include <math.h>

int main() {
   double numbers[] = {1.2, 2.5, 3.7, -1.2, -2.5, -3.7};
   int num_elements = sizeof(numbers) / sizeof(numbers[0]);
   printf("The result of nearest integer is as follows:\n");
   for (int i = 0; i < num_elements; i++) {
       double rounded_value = round(numbers[i]);
       printf("round(%.1f) = %.1f\n", numbers[i], rounded_value);
   }

   return 0;
}

Output

On execution of above code, we get the following result −

The result of nearest integer is as follows:
round(1.2) = 1.0
round(2.5) = 3.0
round(3.7) = 4.0
round(-1.2) = -1.0
round(-2.5) = -3.0
round(-3.7) = -4.0
math_h.htm
Advertisements