一 、第一种方法
先编写一个printfint函数,用来输出整数值。
函数使用了递归调用的,先得到首位整数数值,并输出;再得到中间整数数值,并输出;最后得到末尾整数数值,并输出。
void printfint(int num)
{
if(num == 0)
return ;
printfint(num /10);
putchar(num % 10 + '0');
}
再定义一个printfdouble函数,用来输出double类型的值。
在函数中定义一个int tmpfront 来存储double类型数据小数点左边的数值,
再定义一个int tmpbehind来存储double类型数据小数点右边的数值。
最后用前面的printfint输出 tmpfront + ‘.’ + tmpbehind。
void printfdouble(double num)
{
int tmpfront = (int )num;
int tmpbehind = (int )(10000000 * (num - tmpfront));
if(tmpbehind % 10 > 5)
{
tmpbehind = tmpbehind /10 + 1;
}
else
{
tmpbehind = tmpbehind / 10;
}
printfint(tmpfront);
putchar('.');
printfint(tmpbehind);
}
完整的代码如下:
#include<stdio.h>

这篇博客介绍了两种方法编写Myprintf函数,该函数能处理%d, %f, %s和%c的格式化输出。第一种方法使用递归调用的printfint和printfdouble,结合printf_integer和printf_float打印整数和浮点数。第二种方法利用sprintf生成格式化字符串,然后用fwrite输出到屏幕。"
52933907,5699242,Linux环境下创建与运行程序加载.so动态库,"['Linux开发', 'C/C++编程', '动态库', '软件构建']
最低0.47元/天 解锁文章
3390

被折叠的 条评论
为什么被折叠?



