C_printf

printf()

C/C++ | ShareTechnote

正如你从"Hello World"程序中了解到的,你会知道printf()是一个用于打印你所指定的任何内容的函数。它非常简单易用,但我们经常对需要指定哪种格式才能得到我们想要的正确格式感到困惑。语法非常简单,如下所示:

int printf(const char *format, ...);

我会看起来很简单... 但你会看到关于'*格式'的长长的描述列表,但仅仅阅读整份文档并不会给你带来太多帮助。我认为,比起冗长枯燥的文字,一组没有过多解释的示例会更好。

#include 

 

void main()

{

int d = 123;

float f = 123.45;

 

printf("%d\n",d) ;

printf("%8d\n",d) ;

printf("%08d\n",d) ;

printf("%x\n",d) ;

printf("0x%x\n",d) ;

printf("%#x\n",d) ;

printf("0x%8x\n",d);

printf("%#10x\n",d)  ;

printf("0x%08x\n",d) ;

printf("%#010x\n",d) ;

printf("%#X\n",d) ;

printf("0x%8X\n",d) ;

printf("%#10X\n",d)  ;

printf("0X%08X\n",d) ;

printf("%#010X\n",d) ;

printf("%f\n",f) ;

printf("%8.2f\n",f) ;

printf("%08.2f\n",f) ;

printf("%8.3f\n",f) ;

printf("%08.3f\n",f) ;

 

}

 

Result :------------------------------------


printf("%d",d)         ==>123

printf("%8d",d)        ==>     123

printf("%08d",d)       ==>00000123

printf("%x",d)         ==>7b

printf("0x%x",d)       ==>0x7b

printf("%#x",d)        ==>0x7b

printf("0x%8x",d)      ==>0x      7b

printf("%#10x",d)      ==>      0x7b

printf("0x%08x",d)     ==>0x0000007b

printf("%#010x",d)     ==>0x0000007b

printf("%#X",d)        ==>0X7B

printf("0x%8X",d)      ==>0x      7B

printf("%#10X",d)      ==>      0X7B

printf("0X%08X",d)     ==>0X0000007B

printf("%#010X",d)     ==>0X0000007B

printf("%f",f)         ==>123.449997

printf("%8.2f",f)      ==>  123.45

printf("%08.2f",f)     ==>00123.45

printf("%8.3f",f)      ==> 123.450

printf("%08.3f",f)     ==>0123.450

 

 

printing very big numbers

 

#include 

#include 

 

int main()

{

   long xLong = 2147483647;

   long long xLongLong = 9223372036854775807;

 

   printf("%d\n",xLong);

   printf("%ld\n",xLong);

   printf("\n");

   printf("%d\n",xLongLong);

   printf("%ld\n",xLongLong);

   printf("%lld",xLongLong);

   

   return(0);

}

 

Result :------------------------------------

xLong in (%d) = 2147483647

xLong in (%ld) = 2147483647

 

xLongLong in (%d) = -1

xLongLong in (%ld) = -1

xLongLong in (%lld) = 9223372036854775807

 

 

printing a number in scientific format

 

#include 

#include 

#include 

 

int main()

{

   double xDouble = 2147483647.0;   

 

   printf("%f\n",xDouble);

   printf("%e\n",xDouble);

   printf("%E\n",xDouble);

   printf("%g\n",xDouble);

   printf("%G\n",xDouble);

   

   return(0);

}

 

Result :------------------------------------

xDouble in (%f) = 2147483647.000000

xDouble in (%e) = 2.147484e+009

xDouble in (%E) = 2.147484E+009

xDouble in (%g) = 2.14748e+009

xDouble in (%G) = 2.14748E+009

 

 

你可能感兴趣的:(算法)