为什么不落地返回一个整数? [英] Why doesn't floor return an integer?

查看:91
本文介绍了为什么不落地返回一个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚才我偶然发现了一个事实:在C ++函数地板返回传递给它的同类型,无论是浮动双击或等。

Just now I stumbled upon the fact, that the C++ function floor returns the same type you pass to it, be it float, double or such.

根据这个参考,该函数返回一个四舍五入的整数值。为什么不是这个整数?

According to this reference, the function returns a down rounded integral value. Why isn't this an integer?

推荐答案

由于整型不一定持有相同的积分值作为浮动双击

Because an integral type can't necessarily hold the same integral values as a float or double.

int main(int argc, char *argv[]) {
    std::cout << floor(std::numeric_limits<float>::max()) << std::endl;
    std::cout << static_cast<long>(floor(std::numeric_limits<float>::max())) << ::endl;
}

输出(在我的x86_64体系)

outputs (on my x86_64 architecture)

3.40282e+38
-9223372036854775808

此外,浮点值可以保存为NaN,+ Inf及-Inf,所有这一切都是由一个地板()操作pserved $ P $。这些值都不可以再与整型psented $ P $。

Additionally, floating-point values can hold NaN, +Inf, and -Inf, all of which are preserved by a floor() operation. None of these values can be represented with an integral type.

int main(int argc, char *argv[]) {
    std::cout << floor(std::numeric_limits<float>::quiet_NaN()) << std::endl;
    std::cout << floor(std::numeric_limits<float>::infinity()) << std::endl;
    std::cout << floor(-std::numeric_limits<float>::infinity()) << std::endl;
}

输出

nan
inf
-inf

这篇关于为什么不落地返回一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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