gpt4 book ai didi

c - float 到缩放整型的转换

转载 作者:行者123 更新时间:2023-11-30 15:03:44 24 4
gpt4 key购买 nike

我下面有一个使用 float D1D2的函数。它们是方程中的变量。

我不想使用 float ,因为我开发的嵌入式平台上的内存有限(浮点库很大)。我只想使用int。因此该函数将返回一个 int 并在计算中使用 int

例如,该函数将返回 229500 度,而不是 22.95 度。

有人知道我如何计算 D1D2 应该变成什么值吗?

函数返回值的取值范围是-40到120度。

int 的大小为 4 个字节。

float readTemperatureC()
{
int val; // Raw value returned from sensor
float temperature; // Temperature derived from raw value

// Conversion coefficients from SHT15 datasheet
const float D1 = -40.0; // for 14 Bit @ 5V
const float D2 = 0.01; // for 14 Bit DEGC

// Fetch raw value
val = readTemperatureRaw();

// Convert raw value to degrees Celsius
temperature = (_val * D2) + D1;

return (temperature);
}

这是我想要转换为仅使用整数的函数。 int readTemperatureC() { 整数值;//传感器返回的原始值 内部温度;//从原始值导出的温度

  // Conversion coefficients from SHT15 datasheet
const int D1 = ?; // for 14 Bit @ 5V
const int D2 = ?; // for 14 Bit DEGC

// Fetch raw value
val = readTemperatureRaw();

// Convert raw value to degrees Celsius
temperature = (val * D2) + D1;

return (temperature);
}

最佳答案

instead of 22.95 degrees the function would return 229500 degrees.

将系数乘以 10,000 并使用整数算术。

// Conversion coefficients from SHT15 datasheet
// const float D1 = -40.0; // for 14 Bit @ 5V
// const float D2 = 0.01; // for 14 Bit DEGC
const int D1 = (int) (-40.0*10000);
const int D2 = (int) (0.01*10000);
...
temperature = (_val * D2) + D1;

注:OP 状态为 4 字节 int .

<小时/>

我怀疑 -40.0 的 FP 值和 0.01查看 data sheet后是正确的

OP有 commented正确 data sheet 。来自第 4.3 节温度

表8
d 1(VDD = 5 伏)= -40.1°C
d 2 = 0.01°C

T = d 1 + d 2 * SO T

#define d1 (-40.1 /* degrees C */)
#define d2 (0.01 /* degrees C/d2a */)

#define T_SCALE 10000
#define T_OFFSET ((int)(d1 * SCALE))
#define T_SLOPE ((int)(d2 * SCALE))

// Sensor output - temperature
// 0 to 0x3FFF (14-bit)
int SOT = readTemperatureRaw();

// temeprature in 1/10,000 degree C
int temperature = (SOT * T_SLOPE) + T_OFFSET;

// With 32-bit `int`, no range issue
// -401000 <= temperature <= 1237300

关于c - float 到缩放整型的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593418/

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