如何使用 putchar 打印浮点值? [英] How to print floating point value using putchar?

查看:16
本文介绍了如何使用 putchar 打印浮点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个嵌入式应用程序,需要打印浮点值.由于空间和其他限制,我只能使用 putchar() 进行输出.

I am working on an embedded application and need to print floating point values. Due to space and other limitations I can only use putchar() for output.

我正在尝试创建一个将浮点数作为参数并使用 putchar() 打印它的函数.我有一个适用于整数值的类似函数.

I am trying to create a function that takes a float as parameter and prints it using putchar(). I have a similar function that works for integer values.

void putLong(long x)
{
    if(x < 0)
    {
        putchar('-');
        x = -x;
    }
    if (x >= 10) 
    {
        putLong(x / 10);
    }
    putchar(x % 10+'0');
}

如何为浮点数创建类似的功能?

How could I make a similar function for floats?

推荐答案

这里有一个可能的解决方案:

Here's a possible solution:

typedef enum
{
    DEC1 = 10,
    DEC2 = 100,
    DEC3 = 1000,
    DEC4 = 10000,
    DEC5 = 100000,
    DEC6 = 1000000,

} tPrecision ;

void putFloat( float f, tPrecision p )
{
    long i = (long)f ;
    putLong( i ) ;
    f = (f - i) * p ;
    i = abs((long)f) ;
    if( fabs(f) - i >= 0.5f )
    {
        i++ ;
    }
    putchar('.') ;
    putLong( i ) ;
    putchar('
') ;
}

你会这样使用它:

putFloat( 3.14159f, DEC3 ) ;

这将输出3.142",注意第三位的四舍五入.

which will output "3.142", note the rounding up of the third digit.

如果您只需要固定的小数位数,则可以取消精度参数并对其进行硬编码.

If you only need a fixed number of decimal places, you can do away with the precision argument and hard-code it.

使用此函数时,您应该注意浮点数只有 6 个有效数字的精度,而不是 6 个小数位.因此,如果您尝试使用 DEC6 打印 123.456,您将在第三位之后得到错误的数字.第 6 位有效数字之后的任何数字都应被忽略,但编写代码以考虑到这一点在您的应用程序中可能是不必要的,或者您希望在您的约束条件下更昂贵.

When using this function you should be aware that a float only has 6 significant digits of precision, not six decimal places. So if you attempt to print say 123.456 using DEC6 you will get erroneous digits after the third place. Any digits after the 6th significant digit should be ignored, but writing the code to take account of that may be unnecessary in your application or more expensive that you would wish given your constraints.

这篇关于如何使用 putchar 打印浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆