How to round floating point numbers to the nearest integer in C?

前端 未结 11 681
鱼传尺愫
鱼传尺愫 2020-12-16 04:03

Is there any way to round numbers in C?

I do not want to use ceil and floor. Is there any other alternative?

I came across this code snippet when I Googled f

11条回答
  •  死守一世寂寞
    2020-12-16 04:24

    4.9 + 0.5 is 5.4, which cannot possibly round to 4 unless your compiler is seriously broken.

    I just confirmed that the Googled code gives the correct answer for 4.9.

    marcelo@macbookpro-1:~$ cat round.c 
    #include 
    
    int main() {
        float num = 4.9;
        int n = (int)(num < 0 ? (num - 0.5) : (num + 0.5));
        printf("%d\n", n);
    }
    marcelo@macbookpro-1:~$ make round && ./round
    cc     round.c   -o round
    5
    marcelo@macbookpro-1:~$
    

提交回复
热议问题