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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现printf 浮点数打印 -- 待解决相关的知识,希望对你有一定的参考价值。

#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 浮点数打印 -- 待解决的主要内容,如果未能解决你的问题,请参考以下文章

printf函数的类型转换问题

Printf 用于 c 中的浮点数

STM32 Printf 打印浮点数乱码的问题

STM32 Printf 打印浮点数乱码的问题

STM32 Printf 打印浮点数乱码的问题

STM32 Printf 打印浮点数乱码的问题