關於一道IEEE754浮點數標準的百度面試題再論

來源:互聯網
上載者:User
請猛戳出處!作者解釋的很清楚,看完之後,拿出手邊的CSAPP,翻開2.4.2節的”IEEE浮點表示“P70-73一節再次默默觀看並將代碼敲到VS裡面看看記憶體中是不是真的如作者所說。 面試題代碼
1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main(void)
{
    double a = 10;
    printf("a = %d\n", a);
    
    return 0;
}
結果確實如此。然後,看完之後,順便想看看float的如何,就把double改成float,發現結果竟然輸出還是為0,但是記憶體觀看器中卻不是0,是如IEEE754規定的數值。 C++ Code 
1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main(void)
{   
    float a = 10.0;
    printf("%x \n",a);

    return 0;
}

難道是因為編譯器做了某些最佳化,看看在“float a = 10.0;”前面加上“volatile”,讓編譯器每次都從記憶體中讀取資料,結果還是0。 C++ Code 
1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main(void)
{   
    volatile float a = 10.0;
    printf("%x \n",a);

    return 0;
}

沒辦法,只能用指標了,代碼修改如下: C++ Code 
1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(void)
{   
    float a = 10.0;
    int* pa =&a;
    printf("%x \n",*pa);

    return 0;
}

嗯,這下結果按照IEEE754來的話就完全對了。0 100000100 100000 00000000 0000000s exp             frac                    
                 
但是,這是為什麼呢?此處我加上volatile來屏蔽掉寄存器的最佳化,但結果依舊,難道是編譯器在這中間做了什麼事嗎?道行不夠( ⊙ o ⊙ )啊!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.