0

我的功能没有按预期工作。目标是将嵌入式设备(带 LCD)上的人类可读的物理单元字符串打印到缓冲区中。例如1234uV,应显示为+1.234mVwhere -100023uVas -1.000,230 V。通过可选的正确调整(at)如何正确(快速和安全)实施uV

uint8 voltage_string(char* buf, int32 uVolt)
{
    static const int32 VOLT = 1000000;
    static const int32 MILLIVOLT = 1000;

    const int32  V =  uVolt / VOLT;
    const int32 mV = (uVolt - V*VOLT) / MILLIVOLT;
    const int32 uV = (uVolt - V*VOLT - mV*MILLIVOLT);

    uint8 n = 0;

    if(abs(V) > 0) {
        n  = sprintf(buf,     "%+d",    V);
        n += sprintf(buf + n, ",%3d",   abs(mV));
        n += sprintf(buf + n, ".%3d V", abs(uV));

        return n;
    }

    if(abs(mV) > 0) {
        n  = sprintf(buf,     "%+d",     mV);
        n += sprintf(buf + n, ",%3d mV", abs(mV));

        return n;
    }

    if(abs(uV) > 0) {
        n  = sprintf(buf,     "%+3d uV", uV);

        return n;
    }

    return n;
}
4

2 回答 2

0

您的代码比它需要的要复杂得多 - 您可以将其简化为如下所示:

uint8_t voltage_string(char* buf, int32_t uVolt)
{
    const int32_t VOLT = 1000000;
    const int32_t MILLIVOLT = 1000;

    uint8_t n = 0;

    if (abs(uVolt) >= VOLT)
    {
        n = sprintf(buf, "%+.6f V", uVolt / (double)VOLT);
    }
    else if (abs(uVolt) >= MILLIVOLT)
    {
        n = sprintf(buf, "%+.3f mV", uVolt / (double)MILLIVOLT);
    }
    else
    {
        n = sprintf(buf, "%+d µV", uVolt);
    }

    return n;
}
于 2012-09-06T10:44:35.363 回答
0
uint8_t voltage_string(char* buf, int32_t uVolt) 
{     
    const int32_t VOLT = 1000000;     
    const int32_t MILLIVOLT = 1000;      
    int v=0,mv=0,uv=0;
    uint8_t n = 0;      
    v = uVolt/VOLT;
    mv = (uVolt % VOLT) / MILLIVOLT;
    uv = (uVolt % VOLT) % MILLIVOLT;
    n = sprintf(buf, "%d.%03d%03d  V", v,mv,uv); 
    return n; 
}
于 2012-09-06T12:38:53.717 回答