round()用于C ++中的float [英] round() for float in C++

查看:185
本文介绍了round()用于C ++中的float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的浮点舍入函数,因此:

  double round 

round(0.1)= 0
round(-0.1)= 0
round(-0.9)= -1
pre>

我可以在math.h中找到ceil()和floor() - 而不是round()。



它存在于另一个名称下的标准C ++库中,或者它缺少了

解决方案

)在C ++ 98标准库中。你可以自己写一个:

 双轮(双d)
{
返回楼层+ 0.5);
}

在C ++ 98标准库中没有循环函数的可能原因它实际上可以以不同的方式实现。以上是一种常见的方式,但还有其他一些,例如 round-to-even ,这种方式较少有偏见,一般更好如果你要做很多舍入;但实现起来有点复杂。


I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find ceil() and floor() in the math.h - but not round().

Is it present in the standard C++ library under another name, or is it missing??

解决方案

There's no round() in the C++98 standard library. You can write one yourself though:

double round(double d)
{
  return floor(d + 0.5);
}

The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as round-to-even, which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though.

这篇关于round()用于C ++中的float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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