Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

rounding - Where is Round() in C++?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use C++11's std::round().

If you are still stuck with older standards, you may use std::floor(), which always rounds to the lower number, and std::ceil(), which always rounds to the higher number.

To get the normal rounding behaviour, you would indeed use floor(i + 0.5).

This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:

double round(double number)
{
    return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}

Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:

#include <iostream>
#include <sstream>

double round(double val, int precision)
{
    std::stringstream s;
    s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
    s >> val;
    return val;
}

Only use the second approach if you are not low on resources and/or need to have control over the precision.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...