我的功能无法按预期工作。目标是在嵌入式设备(带LCD)上将一个人类可读的物理单元串打印到缓冲区中。例如。 1234uV
应显示为+1.234mV
,其中-100023uV
为-1.000,230 V
。如何正确(快速和安全)实施,可选择正确调整(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;
}
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}