How to round floating point number to the nearest integer in C

2 Answers

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

int main()
{
    double x = 4.311, y = 6.500, z = 9.811;

    printf("%ld\n", lround(x));
    printf("%ld\n", lround(y));
    printf("%ld\n", lround(z));

    x = -4.311, y = -6.500, z = -9.811;

    printf("%ld\n", lround(x));
    printf("%ld\n", lround(y));
    printf("%ld\n", lround(z));

    return 0;
}




/*
run:

4
7
10
-4
-7
-10

*/

 



answered May 5, 2021 by avibootz
0 votes
#include <stdio.h>
#include <math.h>

int main()
{
    float x = 4.311f, y = 6.500f, z = 9.811f;

    printf("%.f\n", nearbyintf(x));
    printf("%.f\n", nearbyintf(y));
    printf("%.f\n", nearbyintf(z));

    x = -4.311f, y = -6.500f, z = -9.811f;

    printf("%.f\n", nearbyintf(x));
    printf("%.f\n", nearbyintf(y));
    printf("%.f\n", nearbyintf(z));

    return 0;
}




/*
run:

4
6
10
-4
-6
-10

*/

 



answered Jul 31, 2022 by avibootz
...