5

我想知道为什么这个程序的结果是 5621?

#include <stdio.h>

main()
{
    int i=56;
    printf("%d\n",printf("%d",printf("%d",i)));
    getch();
}
4

5 回答 5

22

printf returns the amount of characters it has printed.

So first the most inner printf gets called with 56, printing 56. Then it returns the amount of characters it has printed (2) to the middle printf, printing 2. Then finally the amount of characters printed (1) gets passed into the outer printf, which then gets printed to procude 5621.

于 2013-07-23T16:48:57.613 回答
9

From the printf man page

Return value

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

56 is printed for the inner printf
2 characters were printed so the argument to the next %d format specifier is 2
1 character was printed by the middle printf so the argument to the outer %d format specifier is 1
Only the outer printf includes a newline so the preceding calls output one after another on the same line, giving 5621\n.

于 2013-07-23T16:48:48.613 回答
6

printf()返回打印的字符数:

printf("%d",i)输出值56
printf("%d",printf("%d",i))输出56,然后2是 中的字符数56
printf("%d\n",printf("%d",printf("%d",i)))输出56,然后2,然后 中的字符数2,即1

于 2013-07-23T16:50:28.757 回答
6

相当于

#include <stdio.h>

main()
{
    int n, i = 56;
    n = printf("%d",i);
    n = printf("%d", n);
    n = printf("%d\n", n);
}

printf 返回写入的字符数。

于 2013-07-23T16:53:39.447 回答
1

The printf() function returns the number of characters that it prints on console.

For example after the following printf call, num_chars will have the value 10 as string "Hi haccks\n" consistes of 10 non-nul characters that will be print on screen.

num_chars = printf("Hi haccks\n");
//                  ^^^^^^^^^ ^ 
//                  12345678910    

Note: \n is single 10th char. So in above code returned value from printf assigned to num_chars variable.

In your code, in the given statement, inner printf() prints the values and then return number of chars that value printed by outer printf as shown below:

// 1              2            3
printf("%d\n", printf("%d", printf("%d",i))); // Here i = 56
         ^              ^            ^    
   print: 1       print: 2         print: 56 
   returns: 1     returns: 1       returns: 2
//    3             2               1        <--Order of printf called 

So it outputs 5621

于 2013-07-23T16:48:23.523 回答