1. 程式人生 > >printf中用%d輸出float或者double

printf中用%d輸出float或者double

首先說一個“預設引數提升”的概念:

If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualied versionof its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.  -- C11 6.5.2.2  Function calls (6)

在可變長引數函式(例如printf函式)或者不帶原型宣告函式中,在呼叫該函式時C自動進行型別提升(在呼叫函式時如果宣告這個函式那麼則不會提升),提升如下:

——float型別的實際引數將提升到double
——char、short和相應的signed、unsigned型別的實際引數提升到int
——如果int不能儲存原值,則提升到unsigned int
然後,呼叫者將提升後的引數傳遞給被呼叫者。C標準對預設實際引數提升規則有明確規定。也就是說, 帶有可變長引數列表的函式, 絕對不會接受到char型別的實際引數。

相關連結:摸我摸我2摸我3

float a,b;
    a=1.2;
    printf("%d\n",1.2);
    printf("%d",a);

如果是直接給1.2展示,那麼結果是858993459,如果賦值給a來展示,那麼結果為1073741824,why?

第一、1.2在記憶體中是以double型別儲存的,具有64位的長度,但是%d輸出時只能擷取低32位進行輸出。

第二、根據預設引數提升的概念,float型別的引數b被自動提升為double型別,這樣也只能輸出低32位。

但是a提升為double時和1.2在記憶體中預設儲存不一樣,導致了最後結果的不一樣。