我正在絞盡腦汁想弄清楚爲什麼這段代碼沒有得到正確的結果。我正在尋找浮點正負溢出/下溢級別的十六進制表示。本代碼是基於關閉此位點和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