我在 nesC
中有以下函数,据我所知,它与 C
基本相同!
event void AdaptiveSampling.dataAvailable(error_t result, float val, bool isRealData)
{
if(result == SUCCESS)
{
//converting raw ADC to centigrade
centiGrade = -39.60 + 0.01 * val;
//printing the value to serial port
if(isRealData)
{
printf("REAL: Temperature is: %d CentiGrade\r\n", centiGrade); //line 91
printf("%d,R,%d,%d\r\n", _counter, val, centiGrade); //line 92
}
else
{
printf("PEDICTED: Temperature is: %d CentiGrade\r\n", centiGrade); //line 96
printf("%d,P,%d,%d\r\n", _counter, val, centiGrade); //line 97
}
_counter++;
}
else
{
printf("Error reading sensor!");
}
}
并且,在代码顶部我定义了这些变量:
uint32_t _counter;
uint16_t centiGrade;
这是我在构建过程中收到的警告:
AdaptiveSamplingC.nc:92:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘uint32_t’ [-Wformat]
AdaptiveSamplingC.nc:92:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘float’ [-Wformat]
AdaptiveSamplingC.nc:97:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘uint32_t’ [-Wformat]
AdaptiveSamplingC.nc:97:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘float’ [-Wformat]
这是屏幕上输出的示例:
PEDICTED: Temperature is: 26 CentiGrade
291,P,0,-3402
REAL: Temperature is: 26 CentiGrade
292,R,0,4096
PEDICTED: Temperature is: 26 CentiGrade
293,P,0,-1495
问题:
在第 91 行中,我希望看到温度值是 float ...我的意思是像 26.25
这样的东西...但由于某种原因它打印为整数。我尝试将 %d
更改为 %f
但它没有帮助,因为您看到第 92 行和第 97 行中的输出几乎已损坏,原因我还无法弄清楚!
此外,我无法解释为什么第 92 行和第 97 行的行为如此奇怪,以及为什么它们在构建期间会出现警告。
您能告诉我如何改进吗?
最佳答案
您的问题是未定义的行为,这就是您收到警告的原因。警告表明确实有问题。
printf
是一个可变参数函数,因此它需要一些有关参数类型的信息。这就是格式说明符的工作(例如 %d
)。
%d
告诉 printf
期待一个 int
类型参数,您的警告消息告诉您:警告:格式 %d
需要类型为 int
但是,您提供的类型不是 int
。它们是 uint32_t
和 float
,您的警告消息也告诉您:但是参数 2 的类型为 uint32_t
[-Wformat] 和 但参数 3 的类型为 float
[-Wformat]。
有很多解决方案。最好的办法是使用正确的格式说明符!(废话)。 int
为 "%d"
,uint32_t
为 "%"PRIu32
和 "%f"
for double
(float
被提升为)。对于 uint32_t
,您可以转换为 unsigned long
并使用 "%lu"
进行打印。
关于c - C 中 printf 字符串格式的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16899103/