函数在C中分配了不正确的浮点值 [英] Function assigns incorrect float value in C
问题描述
我试图返回一个浮点值并将其分配给一个浮点变量,但是新的浮点值与返回的值不同.
I am trying to return a float value and assign it to a float variable, but the value of the new float is different from the returned one.
float getVoltageReading() {
return 1.2f;
}
void updateUIReadings(uint8_t menuID) {
float integerReading = getVoltageReading(); // digital voltage
}
在调试器中,我看到getVoltageReading返回 1.2
,但是将integerReading分配为 1.06703091e + 009
In debugger I see that getVoltageReading return 1.2
, but the integerReading is assigned to be 1.06703091e+009
那是为什么?
推荐答案
您正在调用 getVoltageReading
函数,而该函数在范围内没有活动的原型,这意味着它假定将返回int
.从问题的组织方式来看,它看起来是在范围内,但我可以向您保证它不在范围内.
You are calling the getVoltageReading
function without an active prototype in scope, which means it is assuming that it will return an int
. It looks like, from the way your question is organised, that it is in scope, but I can assure you it's not.
通过以下两个文件,您可以看到 testprog1.c
:
You can see that with the following two files, testprog1.c
:
#include <stdio.h>
//float getVoltageReading(void);
int main(void) {
float integerReading = getVoltageReading ();
printf("%e\n", integerReading);
return 0;
}
和 testprog2.c
:
float getVoltageReading(void) {
return 1.2f;
}
将它们编译并链接在一起后,输出为:
When these are compiled and linked together, the output is:
1.067031e+09
因为从 getVoltageReading()
返回的浮点值被解释为 int
.如果您在 testprog1.c
中取消注释原型,它会正常工作,因为它将float值解释为 float
:
because the float value being returned from getVoltageReading()
is being interpreted as an int
. If you uncomment the prototype in testprog1.c
, it works fine because it interprets the float value as a float
:
1.200000e+00
这篇关于函数在C中分配了不正确的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!