如何将浮点数四舍五入到 C 中最接近的整数? [英] How to round floating point numbers to the nearest integer in C?

查看:41
本文介绍了如何将浮点数四舍五入到 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:~$

这篇关于如何将浮点数四舍五入到 C 中最接近的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆