如何在C ++中舍入浮点数 [英] How to round floating point number in C++

查看:119
本文介绍了如何在C ++中舍入浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int digit = 1;
float result=0.0;
double temp = 200000;
float tick = 0.00100000005;

result = digit/1000000.0;
long long phase = temp*result*1000/tick*1000





结果将等于9.99999997e-07。如果手动计算它应该是0.000001如何使指数num为0.000001?谢谢。



如果结果= 9.99999997e-07阶段计算将是199999,但是如果结果= 0.000001阶段计算的将是200000.我想得到结果200000但是如何将指数num舍入到0.000001?



result will be equal to 9.99999997e-07. If manually calculate it should be 0.000001 How can I make the exponential num to be 0.000001? Thanks.

if result = 9.99999997e-07 phase calculated will be 199999,however if result = 0.000001 phase calculated will be 200000. I want to get the result 200000 but how can I round the exponential num to 0.000001?

推荐答案

也许这个 [ ^ ]文章会有所帮助。
Perhaps this[^] article will help.


浮点数不精确。 9.99999997e-07是可以表示为float的最接近的数字。使用double可以提供更高的精度...通常足以进行这样的计算。



您还应该以尽可能避免不精确的方式编写表达式。由于浮点数可以精确地表示1到15位数的倍数,但不能精确地表示分数(除了分数如0.25,0.5,0.75和其他分子将是整数且分母的幂为2),它可能最好保持每个值的值并进行最终计算:

Floating points are imprecise. 9.99999997e-07 is the closest number that can be represented as a float. Using a double would give much more precision... often enough for computation like that.

You should also write your expression in a way to avoid as much imprecision as possible. As floating point can represent exactly multiple of 1 up to about 15 digits but cannot represent exactly fractionnal number (except for fraction like 0.25, 0.5, 0.75 and other where the numerator would be an integer and the denominator a power of 2), it might be preferable to keep each value serate and do the final computation:
long long phase = (digit * temp * 1000 * 1000) / (ticks * 1000000.0);



应该注意的是, tick 也应该是 double ,以提高精度。否则,你在那里失去了所有精度。



最后,在某些情况下,你可能还想对结果数进行舍入。这特别是转换回整数的情况。如果相位计算的结果类似于199999.998,则可能需要200000的结果。如果没有舍入,则该值将被截断为199999.


It should be noted that tick should be a double too for improved precision. Otherwise, you loose all your precision there.

Finally, in some cases, you might also want to round the resulting number. This is particulary the case where converting back to integer. If the result of phase computation is something like 199999.998, you probably want a result of 200000. Without rounding, the value would be truncated to 199999.

long long phase = floor((digit * temp * 1000 * 1000) / (ticks * 1000000.0) + 0.5);



当您进行这样的计算时,了解语言规范并了解浮点的工作原理非常有用。理想情况下,这是一种事情,人们可以在scholl中学习,但如果你自己学习,你应该能够在Google上找到很多信息。


When you do computation like that, it is useful to know the language specification and learn how floating points works. Ideally, this is the kind of things, one would learn in scholl but if you are Learning by yourself, you should be able to find a lot of information on Google.


这篇关于如何在C ++中舍入浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆