我写了一个函数来整齐地打印一个浮点值。目前它直接在屏幕上输出它,但在我的代码的其他地方我需要将这个函数的结果存储在一个变量中作为字符串(或 char[])。有什么建议吗?
void printfFloat(float toBePrinted)
{
uint32_t fi, f0, f1, f2;
char c;
float f = toBePrinted;
if (f<0)
{
c = '-';
f = -f;
}
else
{
c = ' ';
}
// integer portion.
fi = (uint32_t) f;
// decimal portion...get index for up to 3 decimal places.
f = f - ((float) fi);
f0 = f*10; f0 %= 10;
f1 = f*100; f1 %= 10;
f2 = f*1000; f2 %= 10;
if(c == '-')
printf("%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
else
printf("%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}
这个函数的返回类型应该是什么?我想在最后做这样的事情:
char[32] buffer;
buffer = printfFloat(_myFloat);
最佳答案
What should be return type of this function?
C 没有 String 数据类型,因此您必须将缓冲区的地址作为参数传递:
char[32] buffer;
printfFloat(_myFloat, buffer);
您的函数将变为:
void printfFloat(float toBePrinted, char *buffer)
{
///rest of code
if(c == '-')
sprintf(buffer, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
else
sprintf(buffer, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}
关于c - 以字符串为返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913647/