gpt4 book ai didi

c - 负数问题

转载 作者:行者123 更新时间:2023-11-30 18:42:48 25 4
gpt4 key购买 nike

我有这个“简单”代码。

union
{
unsigned int res;
char bytes[2];
} ADC;

char ADC_num[5];
float temprature;

void vis_temp (void) // Show temp..
{
signed int l, length;
unsigned int rem;

GO_nDONE=1; // initiate conversion on the channel 0

while (GO_nDONE) continue;

ADC.bytes[0]=ADRESL;
ADC.bytes[1]=ADRESH;

utoa(ADC_num, ADC.res, 10);

temprature = (float) ADC.res * 478.1 / 1024;
temprature = temprature - 50.0;

l = (signed int) temprature;
temprature -= (float) l;
rem = (unsigned int)(temprature* 1e1);

sprintf(&ADC_num, "%i.%u", l, rem);

当读取ADC_res(引脚上的电压,温度传感器)时,温度为 0 度或以下,程序将写入“0.65500”而不是“-3.5”或类似内容。我应该将权利声明为有符号和无符号整数。任何修复它的提示,或者有其他转换它的方法。

最佳答案

temprature = (float) ADC.res * 478.1 / 1024;
temprature = temprature - 50.0;

假设现在temprature的值为负值-x.yz

l = (signed int) temprature;

现在l = -x,并且

temprature -= (float) l;

温度 = -x.yz - (-x) = -0.yz

rem = (unsigned int)(temprature* 1e1);

乘以 10,并转换为 unsigned int。通常,这会导致未定义的行为 (6.3.1.4 (1)):

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.61)

61) The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1, Utype_MAX+1).

但是将负值转换为unsigned int无论如何都会产生错误的结果,即使进行了余数运算,你想要的是绝对值,所以你应该转换

rem = (unsigned int)fabsf(temprature * 1e1);

那里。

关于c - 负数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425155/

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