round() : Nearest integer value of a number

#include <stdio.h>
int main() {
printf("\nNumber = %.2f", round(12.38)); // Number = 12.00
printf("\nNumber = %.2f", round(12.89)); // Number = 13.00
printf("\nNumber = %.2f", round(-12.32)); // Number = -12.00
printf("\nNumber = %.2f", round(-12.95)); // Number = -13.00
return 0;
}
We will get nearest integer part of a decimal value by using round() function. If the decimal part is less than .5 then lower side integer is returned. If decimal part is more than or equal .5 then higher side is returned.
round(x) 
x = input number

Example with integer variables

#include 
#include 
int main(void){
     int  x1,x2,x3,x4;
     x1=round(13.345);
     x2=round(12.656);
     x3=round(-13.21);
     x4=round(-14.67);
     printf("x1=%d , x2=%d,x3=%d,x4=%d", x1,x2,x3,x4);
     return 0;
}
The above code will give this output.
x1=13, x2=13, x3=-13,x4=-15

Example with float variables

#include <stdio.h>
#include <math.h>
int main(void){
     float  x1,x2,x3,x4;
     x1=round(13.545);
     x2=round(12.656);
     x3=round(-13.51);
     x4=round(-14.67);
     printf("x1=%f , x2=%f,x3=%f,x4=%f", x1,x2,x3,x4);
     return 0;
}
Output is here
x1=14.000000, x2=13.000000, x3=-14.000000,x4=-15.000000

Example 1: Rounding Positive and Negative Numbers

This example demonstrates how to use round() to round positive, negative, and zero values.

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

int main() {
    double num1 = 9.75, num2 = -9.25, num3 = 0.0;
    
    printf("round(%.2f) = %.2f\n", num1, round(num1));
    printf("round(%.2f) = %.2f\n", num2, round(num2));
    printf("round(%.2f) = %.2f\n", num3, round(num3));
    
    return 0;
}
Output:
round(9.75) = 10.00
round(-9.25) = -9.00
round(0.00) = 0.00
---

Example 2: Rounding Values with User Input

Allow users to input a number and see its rounded value using round().

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

int main() {
    double num;
    
    printf("Enter a number: ");
    scanf("%lf", &num);
    
    printf("The rounded value is: %.2f\n", round(num));
    
    return 0;
}
Output:
Enter a number: 5.67
The rounded value is: 6.00
---

Example 3: Rounding an Array of Numbers

This example rounds an array of floating-point numbers.

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

int main() {
    double nums[] = {3.14, -2.73, 5.99, -7.01};
    int n = sizeof(nums) / sizeof(nums[0]);
    
    for (int i = 0; i < n; i++) {
        printf("round(%.2f) = %.2f\n", nums[i], round(nums[i]));
    }
    
    return 0;
}
Output:
round(3.14) = 3.00
round(-2.73) = -3.00
round(5.99) = 6.00
round(-7.01) = -7.00


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com






    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer