我正在绞尽脑汁想弄清楚为什么这段代码没有得到正确的结果。我正在寻找浮点正负溢出/下溢级别的十六进制表示。本代码是基于关闭此位点和Wikipedia entry:浮点限制代码不能产生正确的结果
7f7f FFFF≈3.4028234×10(最大单精度) - 从维基百科条目,对应于正溢出
下面的代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(void) {
float two = 2;
float twentyThree = 23;
float one27 = 127;
float one49 = 149;
float posOverflow, negOverflow, posUnderflow, negUnderflow;
posOverflow = two - (pow(two, -twentyThree) * pow(two, one27));
negOverflow = -(two - (pow(two, one27) * pow(two, one27)));
negUnderflow = -pow(two, -one49);
posUnderflow = pow(two, -one49);
cout << "Positive overflow occurs when value greater than: " << hex << *(int*)&posOverflow << endl;
cout << "Neg overflow occurs when value less than: " << hex << *(int*)&negOverflow << endl;
cout << "Positive underflow occurs when value greater than: " << hex << *(int*)&posUnderflow << endl;
cout << "Neg overflow occurs when value greater than: " << hex << *(int*)&negUnderflow << endl;
}
的输出是:
正发生溢出时VA略大于:当值大于
7f800000
正溢时:当值小于发生f3800000
负片溢出1
负片溢出时发生值大于:80000001
为了让浮点的十六进制表示,我正在使用描述的方法here:
为什么代码不工作?我知道如果积极溢出= 7f7f ffff
它会起作用。
你应该使用'double'而不是'float'。 – 2013-02-18 03:19:11
@LokiAstari你不能简单地将'double'替换成这个代码,所有的表达式都需要改变,因为它们以不同的值溢出和下溢。另外,由于这段代码的目的似乎是对IEEE浮点的更好的理解,我认为'float'正是他应该使用的。 – 2013-02-18 03:58:40