How to print floating point value using putchar?

后端 未结 3 1479
面向向阳花
面向向阳花 2021-01-06 20:03

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.

I am trying

3条回答
  •  渐次进展
    2021-01-06 20:13

    What range of values and accuracy/precision requirements do you need? Printing the exact value of a floating point number in decimal is a very hard problem and requires up to 8 kb or so (I could be off by a few powers of 2; this is off the top of my head) of working space if you support 80-bit or 128-bit long double values. You can probably get by with 1 kb or so if you only support double, and essentially no working space if you just want to print poor approximations.

    OK, so here's a really basic version:

    void putDouble(double x, int p)
    {
        long d;
        if (x<0) {
            putchar('-');
            x=-x;
        }
        d = x;
        putLong(d);
        putchar('.');
        while (p--) {
            x = (x - d) * 10;
            d = x;
            putchar('0'+d);
        }
    }
    

    You might want to fix your putLong to handle numbers longer than 2 digits, 2. :-)

提交回复
热议问题