关于printf

1860阅读 0评论2013-04-24 lzj123
分类:C/C++

printf函数的一些使用方法。

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. #define SHORT_MAX 0x7FFF
  3. #define INT_MAX 0x7FFFFFFF
  4. #define LONG_MAX 0x7FFFFFFFFFFFFFFF

  5. void print_d()
  6. {
  7.     int i = 10;
  8.     int j = -10;

  9.     printf("|%.5d|\n", i);
  10.     printf("|%05d|\n", i);

  11.     printf("|%.5d|\n", j);
  12.     printf("|%05d|\n", j);

  13.     printf("|%5d|\n", i);
  14.     printf("|%-5d|\n", i);

  15.     printf("|%+d|\n", i);

  16.     printf("|%*.*d|\n", 5, 3, i);

  17.     printf("%hd\n", SHORT_MAX);
  18.     printf("%d\n", INT_MAX);
  19.     printf("%ld\n", LONG_MAX);

  20.     printf("|% d|\n", i);
  21.     printf("|% d|\n", j);

  22.     printf("\n");
  23. }

  24. void print_s()
  25. {
  26.     char* str = "abcde";

  27.     printf("|%5.3s|\n", str);
  28.     printf("|%-5.3s|\n", str);

  29.     printf("|%*.*s|\n", 5, 3, str);

  30.     printf("\n");
  31. }

  32. void print_f()
  33. {
  34.     float f = 11.23456;
  35.     double df = 11.23456;
  36.     long double ldf = 99999999999998.4111111111;

  37.     printf("|%f|\n", f);
  38.     printf("|%f|\n", df);

  39.     printf("|%7.3f|\n", f);
  40.     printf("|%7.3f|\n", df);
  41.     printf("|%*.*f|\n", 7, 3, f);
  42.     printf("|%*.*f|\n", 7, 3, df);

  43.     printf("|%'Lf|\n", ldf);
  44.     printf("|%'.4Lf|\n", ldf);

  45.     printf("%e\n", df);
  46.     printf("%g\n", df);

  47.     printf("\n");
  48. }

  49. void print_o()
  50. {
  51.     int i = 10000;

  52.     printf("%x\n", i);
  53.     printf("%o\n", i);

  54.     printf("%#x\n", i);
  55.     printf("%#o\n", i);

  56.     printf("\n");
  57. }

  58. int main(int argc, char *argv[])
  59. {
  60.     print_d();

  61.     print_f();
  62.     
  63.     print_s();

  64.     print_o();

  65.     return 0;
  66. }
下面是执行结果

|00010|
|00010|
|-00010|
|-0010|
|   10|
|10   |
|+10|
|  010|
32767
2147483647
9223372036854775807
| 10|
|-10|

|11.234560|
|11.234560|
| 11.235|
| 11.235|
| 11.235|
| 11.235|
|99999999999998.406250|
|99999999999998.4062|
1.123456e+01
11.2346

|  abc|
|abc  |
|  abc|

2710
23420
0x2710
023420


上一篇:gdb备忘
下一篇:一些命令使用方法