簡體   English   中英

C 中 printf() function 的返回值

[英]Return value of printf() function in C

printf() function 將返回打印的字符數。 但是在下面的代碼中為什么打印 5。

int a=1000;
printf("%d",printf("\n%d",a));

它打印一次“1000”和一個空格,所以我們總共有 2 個字符。

它應該是 output “1000 2”。 但它輸出“1000 5”。

output 的字符數為1000為四個字符。 \n是一個字符。

printf不會像scanf系列函數一樣返回“項目”的數量 output 用於輸入。 它返回實際的字符數。

內部調用首先發生,打印 5 個字符( \n1000 )並返回5

然后發生外部調用,並打印內部調用返回的5

假設表達式:

int a=10;
printf("a=%d",printf("b=%d",a));

output

b=10 a=4;

b因為賦值給 b ie

b=10;

b,=,1,0   

計為四並分配給 a 即:

a=4;

讓我們首先檢查內部 printf 的 output:

/n, 1, 0, 0, 0

現在你需要考慮兩件事:

1) You have to take escape sequences like '\n','\t' etc into account.
2) You have to take 1 escape sequence as 1 character (not 2)

外部 printf 返回內部 printf 的實際字符數,即 5。所以外部 printf 返回 5。

printf()返回實際角色計數,在這里我們有4 (“ 1000”) + 1 (“ \ n”)字符,因此它將給出output 1000,然后是5個角色計數,是Inner ZAFA0FF8B27B27666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666abde像10005

您應該清楚地注意到1000是 4 個字母,並且您有\n它本身就是一個字符

數字 1000 由四位數字組成,因此打印它需要四個字符。 四個字符加上換行符是五個字符。

printf("%d",printf("\n%d",a)); printf("\n%d",a)將打印一個換行符'\n'和 integer 值1000 ,總共5字符。 首先調用第一個內部printf打印換行符和 1000,然后由外部printf打印返回值5

Printf 返回 function 成功打印的字符數。

printf() 返回總數。 在控制台上打印的字符,您通過 1000; 所以第一個內部 printf() function 將工作並打印 1000,這里沒有。 字符數是 4。一個是 \n。

所以總沒有。 字符變為 5,這就是它打印 1000 5 的原因。

在此處輸入圖像描述

正如您在圖像中看到的,首先最后一個 printf 顯示它應該顯示的內容,即 3223433 1233。現在,最后一個 printf 返回它顯示的字符串/int 中的字符數。 Then, the second last printf displays 12 which is the length of the whatever is displayed by last printf ie 3223433 1233. The third last printf now displays 2 which is the length of 12. Since, length of 12 is 2, it is displayed next然后由於 2 的長度為 1,因此顯示 1,最后再次顯示 1,因為它是 1 的長度。

再補充一點, printf()返回的字符數可能取決於參數的說明符

前任:

int a= 0xff;
printf(" : %i characters\n" ,printf("%x",a)); //prints ff : 2 characters
printf(" : %i characters\n" ,printf("%d",a)); //prints 255 : 3 characters
int a=1000;
printf("%d",printf("\n%d",a));

此代碼片段中有 2 個 printf() 函數:

  1. 內部 printf()
  2. 外部 printf()

首先,內部 printf() 將執行並打印1000 ,然后外部 printf() 將執行。

需要注意的是, printf()返回它打印的字符數,並且轉義序列在 printf() 中被計為一個字符

因此,通過執行內部 printf(),我們得到了 5(因為 '\n', 1, 0,0,0 是 5 個字符),現在,當執行外部 printf() 時,會打印 5。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM