简体   繁体   English

函数在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
}

In debugger I see that getVoltageReading return 1.2 , but the integerReading is assigned to be 1.06703091e+009 在调试器中,我看到getVoltageReading返回1.2 ,但integerReading被分配为1.06703091e+009

Why is that? 这是为什么?

You are calling the getVoltageReading function without an active prototype in scope, which means it is assuming that it will return an int . 您正在调用getVoltageReading函数,而没有在范围内使用活动的原型,这意味着它假设它将返回一个int It looks like, from the way your question is organised, that it is in scope, but I can assure you it's not. 从您的问题的组织方式来看 ,它似乎在范围内,但我可以向您保证。

You can see that with the following two files, testprog1.c : 您可以通过以下两个文件testprog1.c看到它:

#include <stdio.h>

//float getVoltageReading(void);

int main(void) {
    float integerReading = getVoltageReading ();
    printf("%e\n", integerReading);
    return 0;
}

and testprog2.c : testprog2.c

float getVoltageReading(void) {
    return 1.2f;
}

When these are compiled and linked together, the output is: 将它们编译并链接在一起后,输出为:

1.067031e+09

because the float value being returned from getVoltageReading() is being interpreted as an int . 因为从getVoltageReading()返回的float值被解释为int If you uncomment the prototype in testprog1.c , it works fine because it interprets the float value as a float : 如果您在testprog1.c取消注释原型,则它将正常工作,因为它将float值解释为float

1.200000e+00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM