如何在现代C ++中将float转换为int [英] How to convert a float to an int in modern C++

查看:172
本文介绍了如何在现代C ++中将float转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来很奇怪,我找不到如何干净地将 float 转换为 int

这个技巧

  int int_value =(int)(float_value + 0.5); 

触发a

 警告:在gcc中使用旧式的

b
$ b

那么,将 float 转换为 int ? (我接受精确度的损失当然是)

解决方案

正如Josh在评论中指出的那样, + 0.5 不是很可靠。为了提高安全性,您可以像下面这样将 static_cast std :: round 结合:

  int int_value = static_cast< int>(std :: round(float_value)); 

对于演员角色,请参阅这个优秀的帖子作为解释。


As strange as it may seems, I can't find how to cleanly convert a float to an int.

This technique

int int_value = (int)(float_value + 0.5);

triggers a

warning: use of old-style cast

in gcc.

So, what is the modern-style, simple way to convert a float to an int ? (I accept the loss of precision of course)

解决方案

As Josh pointed out in the comments, + 0.5 is not very reliable. For extra security you could combine a static_cast with std::round like so:

int int_value = static_cast<int>(std::round(float_value));

For the casting part, see this excellent post for an explanation.

这篇关于如何在现代C ++中将float转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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