关于printf() 使用时遇到的4个疑问。
程序代码:/* Demonstrateion of printf(). */
/* 代码是书上的代码 ,个人用的是 DEV-C ++ 编译器编写代码 */
#include<stdio.h>
char *m1 = "Binary";
char *m2 = "Decimal";
char *m3 = "Octal";
char *m4 = "Hexadecimal";
int main( void )
{
float d1 = 10000.123;
int n, f;
puts("Outputting a number with different field widths.\n");
/* 以下为疑问 1、2、3 的代码*/
printf("%5f\n", d1);
printf("%10f\n", d1);
printf("%15f\n", d1);
printf("%20f\n", d1);
printf("%25f\n", d1);
puts("\n Press Enter to continue...");
fflush(stdin);
getchar();
puts("\nUse the * field width specifier to obtain field width");
puts("from a variable in the argument list.\n");
for (n=5; n<=25; n+=5)
printf("%*f\n", n, d1);
puts("\n Press Enter to continue...");
fflush(stdin);
getchar();
puts("\nInclude leading zeros.\n");
printf("%05f\n", d1);
printf("%010f\n", d1);
printf("%015f\n", d1);
printf("%020f\n", d1);
printf("%025f\n", d1);
puts("\n Press Enter to continue...");
fflush(stdin);
getchar();
puts("\nDisplay in octal, decimal, hexadecimal.");
puts("Use # to precede octal and hex output with 0 and 0x.");
puts("Use - to left-justify each value in its field.");
puts("First dissplay column labels.\n");
printf("%-15s%-15s%-15s", m2, m3, m4);
/* 以下为疑问 4 的相关代码 */
for (n = 1; n < 20; n++) /* 最后一次迭代时,n 的值是 20 ,并且我觉得 n=20 一直影响到最后一条printf()语句 */
printf("\n%-15d%-#15o%-#15X", n, n, n);
puts("\n Press Enter to continue...");
fflush(stdin); /* 难道 fflush(stdin) 函数没有将 n=20 清除掉么 ??*/
getchar();
puts("\n\nUse the %n conversion command to count characters.\n");
printf("%s%s%s%s%n", m1, m2, m3, m4, &n);
printf("\n\nThe last printf() output %d characters.\n", n); /* 按理说,实际应该是 The last printf() output 29 characters *
* ,书上确实也是29. 实际上编译后程序显示的是 *
* 20 characters ,这个 20 是和前面的 for 语句 *
* 中的 n < 20 是一致的,即如果改成 n < 25 后 *
* 也会有The last printf() output 25 characters ,为什么是这样? */
system("pause");
return 0;
}








