如何通过舍入到最接近的整数将浮点数转换为 Int [英] How to convert a float to an Int by rounding to the nearest whole integer

查看:11
本文介绍了如何通过舍入到最接近的整数将浮点数转换为 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将 float 转换为 Int 通过四舍五入到最接近的可能整数?

Is there a way to convert a float to an Int by rounding to the nearest possible whole integer?

推荐答案

其实 Paul Beckingham 的回答并不完全正确.如果你尝试像 -1.51 这样的负数,你会得到 -1 而不是 -2.

Actually Paul Beckingham's answer isn't quite correct. If you try a negative number like -1.51, you get -1 instead of -2.

math.h 中的函数 round()、roundf()、lround() 和 lroundf() 也适用于负数.

The functions round(), roundf(), lround(), and lroundf() from math.h work for negative numbers too.

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

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