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

查看:112
本文介绍了如何打印浮点值使用的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.

我想创建一个函数,一个float作为参数,并使用的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('\n') ;
}

您会这样使用它:

putFloat( 3.14159f, DEC3 ) ;

这将输出3.142,注意围捕第三位的。

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

如果你只需要小数位的固定数量,你可以做废除了precision参数和硬code吧。

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

在使用此功能,您应该知道,一个浮动只拥有$的显著数字的6 P $ pcision,不是6的小数的。所以,如果您尝试打印123.456说使用DEC6第三位后,你会得到错误的数字。第六显著数字后的任何数字应该被忽略,但写code考虑到可能在你的应用程序不必要或更贵,你都希望给你的约束。

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天全站免登陆