码迷,mamicode.com
首页 > 其他好文 > 详细

实现printf 浮点数打印 -- 待解决

时间:2016-12-10 00:08:09      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:解决   include   i+1   str   typedef   end   unsigned   浮点数   符号   

#include <stdio.h>

void printHex(int integer)
{
unsigned char isnegative = 0,len = 0, intstr[10]={‘\0‘};
if(integer < 0)
{
isnegative = 1;
integer = 0 - integer;
}
if (integer == 0)
intstr[len++] = ‘0‘;
while (integer)
{
intstr[len++] = (integer % 10) + ‘0‘;
integer = integer / 10;
}
if(isnegative)
intstr[len++] = ‘-‘;
//注意这个k的数据类型 使用k >= 0;为结束条件,k是有符号类型,若是无符号类型,k值回滚到最大值
for(len = len; len > 0; len--)
{
printf("%c", intstr[len-1]);
//UartSend(UART1,intstr[len-1],1);
}
}

void printFlt(float flt, int len)
//void printFlt(float flt)
{
int integer;
integer = (int)flt;
printHex(integer);
printf(".");
//UartSend(UART1,".",1);

flt = flt - integer;
while(flt && len-- )
//while(flt)
{
flt = flt * 10;
integer = (int)flt + ‘0‘;
flt = flt - integer;
printf("%c",integer);
//UartSend(UART1,&integer,1);
}
printf("\n");
}

int main(void)
{
float fNum = 1.12;
printFlt(fNum, 3);

return 0;
}

 

------------------------------------------------------------------------------------------------------------------------

#include<stdio.h>
typedef unsigned char uint8;
typedef unsigned int uint32;

uint8 Float2Char(float value, uint8 *array);

void main()
{
uint8 A[20];
//float value= -123.456789;
float value= -123.00152;
uint8 i;
Float2Char(value, A);
printf("%s",A);
printf("\n");
}


uint8 Float2Char(float value, uint8 *array)
{
float DecimalPart;
uint32 IntegerPart;
uint8 i = 0, j = 0, temp;
//分离整数和小数
if(value< 0)
{
value = -value ;
array[i++] = ‘-‘;
}
else
array[i++] = ‘+‘;

IntegerPart = (uint32)value;
DecimalPart = value - IntegerPart;

//处理整数
if(0 == IntegerPart)//整数部分为0
array[i++] = ‘0‘;
else
{
while(0 != IntegerPart)
{
array[i++] = IntegerPart % 10 + ‘0‘;
IntegerPart /= 10;
}
i--;
for(j = 1; j < (i+1) / 2; j++)
{
temp = array[j];
array[j] = array[i -j+1];
array[i-j+1] = temp;
}
i++;
}


array[i++] = ‘.‘;
//处理小数
array[i++] = (uint32)(DecimalPart * 10) % 10 + ‘0‘;
array[i++] = (uint32)(DecimalPart * 100)%10 + ‘0‘;
array[i++]= (uint32)(DecimalPart * 1000)%10 + ‘0‘;
array[i++] = (uint32)(DecimalPart * 10000)%10 + ‘0‘;
array[i] = ‘\0‘;
return i;
}

 

实现printf 浮点数打印 -- 待解决

标签:解决   include   i+1   str   typedef   end   unsigned   浮点数   符号   

原文地址:http://www.cnblogs.com/iczelion/p/6151922.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!