[英]Function with string as return type
我写了一个函数来整齐地打印浮点值。 目前它直接在屏幕上输出它,但在我的代码中的其他地方我需要将此函数的结果存储在变量中作为字符串(或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);
这个函数应该返回什么类型?
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);
}
看看asprintf ,它会为你分配一个缓冲区并填充它。
char *printfFloat(float toBePrinted)
{
uint32_t fi, f0, f1, f2;
char c;
char *ret = NULL;
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 == '-')
asprintf(&ret, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
else
asprintf(&ret, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
return ret;
}
主要:
#include <stdio.h>
int main()
{
char *ret = printfFloat(42.42);
puts(ret); // print ret
free(ret);
return 0;
}
您可以使用sprintf
函数 。
char buffer[32];
sprintf(buffer, "%f", your_float);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.