简体   繁体   English

为什么我从 std::cout 得到如此精确的浮点数?

[英]Why do I get so precise floating-point number from std::cout?

The program该程序

int main ()
{
    long long ll = LLONG_MAX;
    float f = ll;
    std::cout << ll << '\n';
    std::cout << std::fixed << f << '\n';
    return 0;
}

gives:给出:

9223372036854775807
9223372036854775808.000000

How is it possible?这怎么可能? If 23-bit mantissa can have only 8,388,607 maximum value, why does cout output a 64-bit number?如果 23 位尾数只能有 8,388,607 个最大值,为什么 cout 输出一个 64 位数字?

You stored 2^63-1 in a float, which was rounded to 2^63 = 9223372036854775808. The powers of 2 are exactly representable.您将 2^63-1 存储在浮点数中,该浮点数四舍五入为 2^63 = 9223372036854775808。2 的幂是完全可以表示的。

The nearest number which is exactly representable is 2^63 + 2^40 = 9223373136366403584.可以精确表示的最接近的数字是 2^63 + 2^40 = 92233731363666403584。

long long for you is a 64 bit data type so that means LLONG_MAX has a value of 2^63 - 1 . long long对您来说是 64 位数据类型,因此这意味着LLONG_MAX的值为2^63 - 1 You are right in that this can't be stored in a float which only has 23 bits of mantissa, but 2^63 , which is one more than LLONG_MAX is easily stored in a float.您是对的,因为它不能存储在只有 23 位尾数的float中,但是2^63LLONG_MAX多 1 很容易存储在浮点数中。 It stores 2 in the mantissa and 63 in the exponent and there you have it.它将2存储在尾数中,将63存储在指数中,这样就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 精确的浮点&lt; - &gt;字符串转换 - Precise floating-point<->string conversion 带有浮点数的 std::cout - std::cout with floating number 为什么将tolower()的结果流传输到std :: cout时却得到一个数字,而不是使用putchar()时却得到数字? - Why do I get a number when I stream the result of tolower() to std::cout, but not when I use putchar()? 为什么cout.precision()增加浮点数的精度? - Why does cout.precision() increase floating-point's precision? 获得接近2次幂的快速方法(浮点数) - Fast way to get a close power-of-2 number (floating-point) 为什么我得到错误“&#39;cout&#39;在命名空间&#39;std&#39;中没有命名类型”当我使用“使用cout = std :: cout;”? - Why do I get error “'cout' in namespace 'std' does not name a type” when I use “using cout = std::cout;”? 如何使用GMP创建浮点数组? - How do I use GMP to create a floating-point array? 为什么浮点数没有可用的字节序转换方法? 另外,为什么浮点数无需转换就可以工作? - Why is there no available byte order conversion method for floating-point numbers? Also, why do floating-point numbers work without conversion? 浮点数的确切值作为理性值 - Exact value of a floating-point number as a rational 最大可表示负浮点数 - Largest representable negative floating-point number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM