嵌入式 实现自己的printf函数小示例

my_printf.h:

  1. extern voidmy_printf(const char*format,...);
extern void my_printf(const char *format,...);


my_printf.c:

  1. #include "my_printf.h"
  2. #include"stdarg.h"
  3. voidprintch(const charch)
  4. {
  5. putchar(ch);
  6. }
  7. voidprintint(const intdec)
  8. {
  9. if(dec ==0)
  10. {
  11. return;
  12. }
  13. printint(dec / 10);
  14. putchar((char)(dec % 10 +'0'));
  15. }
  16. voidprintstr(const char*ptr)
  17. {
  18. while(*ptr)
  19. {
  20. putchar(*ptr);
  21. ptr++;
  22. }
  23. }
  24. voidprintfloat(const floatflt)
  25. {
  26. int tmpint =(int)flt;
  27. int tmpflt =(int)(100000 * (flt -tmpint));
  28. if(tmpflt % 10 >=5)
  29. {
  30. tmpflt = tmpflt / 10 + 1;
  31. }
  32. else
  33. {
  34. tmpflt = tmpflt / 10;
  35. }
  36. printint(tmpint);
  37. putchar('.');
  38. printint(tmpflt);
  39. }
  40. voidmy_printf(const char*format,...)
  41. {
  42. va_list ap;
  43. va_start(ap,format);
  44. while(*format)
  45. {
  46. if(*format !='%')
  47. {
  48. putchar(*format);
  49. format++;
  50. }
  51. else
  52. {
  53. format++;
  54. switch(*format)
  55. {
  56. case 'c':
  57. {
  58. char valch =va_arg(ap,int);
  59. printch(valch);
  60. format++;
  61. break;
  62. }
  63. case 'd':
  64. {
  65. int valint =va_arg(ap,int);
  66. printint(valint);
  67. format++;
  68. break;
  69. }
  70. case 's':
  71. {
  72. char *valstr =va_arg(ap,char *);
  73. printstr(valstr);
  74. format++;
  75. break;
  76. }
  77. case 'f':
  78. {
  79. float valflt =va_arg(ap,double);
  80. printfloat(valflt);
  81. format++;
  82. break;
  83. }
  84. default:
  85. {
  86. printch(*format);
  87. format++;
  88. }
  89. }
  90. va_end(ap);
  91. }
  92. }
  93. }
  94. intmain()
  95. {
  96. char ch ='A';
  97. char *str ="holleworld";
  98. int dec =1234;
  99. float flt =1234.3456789;
  100. my_printf("str = %s,dec = %d,ch = %c,flt =%f\n",str,dec,ch,flt);
  101. return 0;
  102. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值