简单实现printf函数
2015-11-27 12:40
288 查看
使用可变参数列表简单实现printf函数
代码如下:
my_print.h
/*
******************
头文件
******************
*/
function.c
/*
*****************
函数功能实现的源文件
*****************
*/
test.c
/*
*******
测试函数
*******
*/
代码如下:
my_print.h
/*
******************
头文件
******************
*/
<span style="font-size:18px;">
#ifndef __PRINT_H__ #define __PRINT_H__ #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<stdarg.h> //#include<string.h> #include<math.h> #define MAX 6 //处理浮点数的小数部分的位数 /* 处理字符的函数 */ void printchar(const char ch); /* 处理整形的函数 */ void printint(const int in); /* 处理字符串的函数 */ void printstr(const char *str); /* 处理浮点数 */ void printfloat(const float fl); /* 自己的printf函数 使用可变参数列表实现 */ void my_printf(const char *format,...); #endif //__PRINT_H__</span>
function.c
/*
*****************
函数功能实现的源文件
*****************
*/
<span style="font-size:18px;">
#include "my_print.h" /* 如果接收的是字符类型 则使用putchar()输出到屏幕 */ void printchar(const char ch) { putchar(ch); } /* 如果是整形数则通过递归将其每一位转变为字符输出 */ void printint(const int in) { if (in < 10) { putchar(in % 10 + '0'); return; } printint(in / 10); putchar(in % 10 + '0'); } /* 如果是字符串则找字符串结束标志 */ void printstr(const char *str) { while (*str) putchar(*str++); } /* 处理浮点数 首先处理整数部分 **************** 在处理小数部分 这里只处理到小数点后6位,其余位缺省掉 */ void printfloat(const float fl) { int i = 0; printint((int)(fl)); //处理整数部分 putchar('.'); //处理小数部分 for (i = 1; i <= MAX; i++) { //通过强制类型转换的巧妙应用按顺序打印想输出的小数位数 putchar(((int)((fl - (int)fl)*pow((int)10, i))) % 10 + '0'); } } /* 自己的printf函数具体实现 */ void my_printf(const char *format,...) { va_list arg; char ch; int in; char *str; float fl; va_start(arg, format); //4 while (*format) { if (*format != '%') { putchar(*format); format++; } else { format++; switch (*format) { case 'c': ch = va_arg(arg, char); printchar(ch); format++; break; case 'd': in = va_arg(arg, int); printint(in); format++; break; case 's': str = va_arg(arg, char*); printstr(str); format++; break; case 'f': fl = va_arg(arg, double); printfloat(fl); format++; break; default: format--; putchar(*format); format++; break; } } } va_end(arg); } </span>
test.c
/*
*******
测试函数
*******
*/
<span style="font-size:18px;">
#include "my_print.h" int main() { int in = 123; char ch = 'm'; char str[] = "asdfg"; float fl = 1.23; printf("%d %c %s %f\n", in, ch, str, fl); my_printf("%d %c %s %f\n", in, ch, str, fl); system("pause"); return 0; } </span>结果如下:
相关文章推荐
- 1066. Root of AVL Tree (25)
- 专业程序员必习:最牛B的编码套路
- 调查内存剩余太少的问题
- 谈谈CS英文论文写作
- CodeForces 601A The Two Routes(dijkstra最短路)——Codeforces Beta Round #333 (Div.1 Div. 2)
- CodeForces 594D REQ(树状数组)
- 关于“一秒一G LiFi比WiFi快一百倍”的评论
- MYSQL数据库的存储过程(Stored Procedure)
- 1064. Complete Binary Search Tree (30)
- 自定义dialog视图
- 地表两个点 的 距离计算公式
- 1064. Complete Binary Search Tree (30)
- React 入门实例教程
- MYSQL数据库的事务(Transaction)
- 安卓游戏开发者:我是如何把包体减了88%
- 232. Implement Queue using Stacks
- dex分包变形记
- 修改PullToRefresh下拉刷新动画
- MYSQL数据库的游标(cursor)
- 一个优质的新闻客户端app