C ++ float to int [英] C++ float to int

查看:506
本文介绍了C ++ float to int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许,这是非常简单的问题,但我不能得到的答案。我已经搜索了一段时间(现在Google认为我发送自动查询 http://twitter.com/michaelsync/status / 17177278608 )..

Maybe, it's very simple question but I couldn't get the answer. I've been searching quite a while ( now Google think that I'm sending automated queries http://twitter.com/michaelsync/status/17177278608 ) ..

int n = 4.35 *100;
cout << n;

为什么输出成为434而不是435? 4.35 * 100 = 435这是一个整数值,这应该可以分配给整数变量n,对不对?

Why does the output become "434" instead of "435"? 4.35 * 100 = 435 which is a integer value and this should be assignable to the integer variable "n", right?

或者C ++编译器在乘法之前将4.35转换为整数吗?我认为它不会。为什么编译器自动将4.35更改为4.34,这仍然是一个float?

OR Does the C++ compiler cast 4.35 to integer before multiplying? I think it won't. Why does the compiler automatically change 4.35 to 4.34 which is still a float??

感谢。

推荐答案

每个计算机科学家应该知道的浮点运算

这真的是只是一个起点,可悲的是,然后语言介绍自己的foibles,当他们做类型转换时,等等。在这种情况下,你只创建了一个情况,常量4.35不能精确表示,因此4.35 * 100更像434.9999999999,并且转换为 int trunc ,而不是 round

That's really just a starting point, sadly, as then languages introduce their own foibles as to when they do type conversions, etc. In this case you've merely created a situation where the constant 4.35 can't be represented precisely, and thus 4.35*100 is more like 434.9999999999, and the cast to int does trunc, not round.

这篇关于C ++ float to int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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