簡単な浮動小数点の丸め関数が必要です。
double round(double);
round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
math.hには,ceil()と
floor()はありますが,`round()はありません。
標準C++ライブラリに別の名前で存在しているのでしょうか、それとも見つからないのでしょうか?
C++98の標準ライブラリにはround()がありません。しかし,自分で書くことはできます。以下は、round-half-upの実装です。
double round(double d)
{
return floor(d + 0.5);
}
C++98の標準ライブラリにround関数がないのは、実際にはさまざまな方法で実装できるからでしょう。上記は一般的な方法の1つですが、他にもround-to-evenのような方法があります。これは、丸めをたくさん行う場合に偏りが少なく、一般的に優れています。
私はこうしました。
#include <cmath.h>
using namespace std;
double roundh(double number, int place){
/* place = decimal point. Putting in 0 will make it round to whole
number. putting in 1 will round to the
tenths digit.
*/
number *= 10^place;
int istack = (int)floor(number);
int out = number-istack;
if (out < 0.5){
floor(number);
number /= 10^place;
return number;
}
if (out > 0.4) {
ceil(number);
number /= 10^place;
return number;
}
}