简体   繁体   English

不需要的舍入C ++

[英]Unwanted rounding C++

I have the following equations: 我有以下等式:

//get thermistor resistor value
temp=(THERMISTOR_R0)/((temp2/temp)-1);

//get temperature value in Kelvins and convert to Celsiuis
temp=(THERMISTOR_BETA)/log(temp/(THERMISTOR_R0*exp((-THERMISTOR_BETA)/298)));
temp-=273;

desiredVoltage =((15700-(25*temp))/10);

THERMISTOR_R0 and THERMISTOR _BETA are constant. THERMISTOR_R0THERMISTOR _BETA是常量。

temp , temp2 and desiredVoltage are unsigned int and are defined before calculations. temptemp2desiredVoltage是unsigned int,在计算之前定义。

The problem is, for example, when the term ((temp2/temp)-1) falls below 1, it rounds down to 0. I want to get rid of this rounding as it is causing huge problems with my calculations. 问题是,例如,当术语((temp2/temp)-1)低于1时,它会向下舍入为0.我想摆脱这种舍入,因为它会导致我的计算出现大问题。

How do I do this? 我该怎么做呢?

It's not rounding, it's integer division. 它不是四舍五入,而是整数除法。 If both operands of the / operator are of integer types the behavior of C++ is to perform an integer division, which keeps only the integer part of the result (this is often needed in some algorithms because it's faster). 如果/运算符的两个操作数都是整数类型,则C ++的行为是执行整数除法,该整数除法仅保留结果的整数部分(这在某些算法中通常需要,因为它更快)。

To get a "regular" division make sure that at least one of the operands involved is of a floating point type ( float , double or long double ); 要获得“常规”除法,请确保所涉及的操作数中至少有一个是浮点类型( floatdoublelong double ); you can do this either declaring the variables involved as FP types 您可以将此参数声明为FP类型

double temp2, temp;

either sticking a cast in front of one of the operands. 要么在其中一个操作数前面贴一个演员。

temp=(THERMISTOR_R0)/((double(temp2)/temp)-1);

(notice that here you'll incur in truncation if temp is still of integral type). (请注意,如果temp仍然是整数类型,那么你将在截断时产生)。

Most probably, here you'll simply want to declare temp and temp2 as double (or float if you are working in a really resource-tight environment). 最有可能的是,在这里你只需要将temptemp2声明为double (如果你在一个非常资源密集的环境中工作,则float )。

Also, when dividing by a numeric literal, keep in mind that if you don't write the decimal point it will be an int literal, if you write it it will be a double . 另外,当用数字文字除以时,请记住,如果你不写小数点,它将是一个int literal,如果你写它,它将是一个double Eg, 298 is an int , 298. is a double , so 1/2 is 0 , but 1/2. 例如, 298int298.double ,所以1/20 ,但是1/2. is 0.5 . 0.5

如果需要浮点除法行为,请确保使用浮点类型。

The compiler rounds floating point values down. 编译器将浮点值向下舍入。

Generally this problem is solved by adding 0.5 to the value before the conversion to an integer. 通常,通过在转换为整数之前将值加0.5来解决此问题。 You may want to explicitly use floating point values (or cast), then add 0.5 to the result before you cast back to integers. 您可能希望显式使用浮点值(或强制转换),然后在转换为整数之前将0.5添加到结果中。

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

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