如何将浮点数四舍五入到 C 中最接近的整数?

问题描述:

有没有办法在 C 中对数字进行四舍五入?

Is there any way to round numbers in C?

我不想使用 ceil 和 floor.还有其他选择吗?

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

我在 Google 上搜索答案时遇到了这个代码片段:

I came across this code snippet when I Googled for the answer:

(int)(num < 0 ? (num - 0.5) : (num + 0.5))

即使 float num =4.9,上面的行也始终将值打印为 4.

The above line always prints the value as 4 even when float num =4.9.

4.9 + 0.5 是 5.4,除非你的编译器严重损坏,否则不可能四舍五入.

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

我刚刚确认 Google 搜索的代码给出了 4.9 的正确答案.

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

marcelo@macbookpro-1:~$ cat round.c 
#include <stdio.h>

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:~$