gpt4 book ai didi

c - 在 C 中将 float 传递给字符串

转载 作者:行者123 更新时间:2023-12-05 08:31:18 26 4
gpt4 key购买 nike

如何将变量添加到字符串中?我想传输具有 depth 实际值的字符串。那么如何将其添加到消息中呢?

float depth = ((pressure) / (g)) * 100;
char message[] = "$DBS,,f,depth,M,,,F*hh<CR><LF>"; //Put actual depth here

最佳答案

我建议使用 snprintf()用法类似于 printf() 和建议的 sprintf(),但是您有一个字符串最大长度的参数。

这样可以避免缓冲区溢出。

depth = ((pressure)/(g))*100;
char message[100];
snprintf(message, sizeof message, "$DBS,,f,%f,M,,,F*hh\r\n", depth );

如果字符串比数组大,你可以通过检查返回值来适应这个数组


int length = snprintf(message, sizeof message, "$DBS,,f,%f,M,,,F*hh\r\n", depth );

if (length > sizeof message)
{
//do something to handle if neccessary
}

在链接的文章中,您可以找到可用于修改字符串中 float 格式的说明符和修饰符列表,这非常有用。根据您的数字有多大,您可能希望使用 %e (用于十进制指数表示法或通常称为工程表示法)。此外,您可以影响使用的位数和其他内容。真的值得一试。

或者您可以查看 http://www.cplusplus.com/reference/cstdio/snprintf/http://www.cplusplus.com/reference/cstdio/printf/这对某些人来说更容易理解,但不是那么详细。

关于c - 在 C 中将 float 传递给字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59271056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com