C++ float 变量如何存储不在其范围内的负值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26602107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does float variable store negative values which are not in their range?
提问by Vishnu Vardhan
The range of float
values is 3.4e-38 to 3.4e+38. So the float variables should not store negative values. But float variables are storing negative values. Please explain it to me.
float
值的范围是 3.4e-38 到 3.4e+38。所以浮点变量不应该存储负值。但是浮点变量存储负值。请给我解释一下。
#include<iostream.h>
void main()
{ float ab=-3.456;
cout<<ab; }
Output:
输出:
-3.456
回答by phuclv
The range for single precision float is 2?126≈ 1.18 × 10?38to (2?2?23) × 2127≈ 3.4 × 1038for positive values and similar but reverse for negative values: -3.4 × 1038to -1.18 × 10?38because IEEE-754 uses sign-magnitude format where sign bit is store separately
单精度浮点数的范围是 2 ?126≈ 1.18 × 10 ?38到 (2?2 ?23) × 2 127≈ 3.4 × 10 38正值和类似但负值相反:-3.4 × 10 38到 - 1.18 × 10 ?38因为 IEEE-754 使用符号大小格式,其中符号位单独存储
Read more about it here
在此处阅读更多相关信息
回答by Heavy
These are largest and smallest positivevalues.
这些是最大和最小的正值。
In the internal representation, there is 1 bit for the sign (S), 8 bits for the exponent (E), and 23 bits for the fraction (F). The bits are mapped with the fraction in bit 0 to bit 22, the exponent in bit 23 to bit 30, and the sign in bit 31.
在内部表示中,符号 (S) 有 1 位,指数 (E) 有 8 位,分数 (F) 有 23 位。这些位通过位 0 到位 22 中的小数、位 23 中的指数到位 30 以及位 31 中的符号进行映射。
回答by incogn1to
Basically float consists of three numbers
基本上浮点数由三个数字组成
significant * base ^ exponent
Significant part and exponent part both can have their separate sign. So actually float range is:
显着部分和指数部分都可以有单独的符号。所以实际上浮动范围是:
float 32 bits -3.4E+38 to +3.4E+38 about 7 decimal digits