C++ round
27th January Update: as somebody has pointed via email (thanks for that), the function I gave only worked for positive numbers. This is the solution he offered (altered a bit not to give warnings so that you can cut&paste ):
#include <cmath>
int function round(double num) {
char sign = static_cast(num/fabs(num));
return static_cast<int>(sign* (fabs(num)+ 0.5));
}
Actually, the solution I gave first (and then suddenly changed it to the one that only works for positive number...) worked perfectly with both positive and negative too. This is it:
#include <cmath>
int function round(double num) {
return static_cast<int>(floor(num+0.5));
}
I was a bit shocked first, finding out there was no round function in C++.
It didn't fortunately take me long to google a nice substitute for it. It can be as simple as this (Warning: this works for positive numbers only. See above for better solution):
int round(double num) {
return (int)(num+0.5);
}
I may be one of the more dumb and lazy programmers (isn't "laziness" in the flag of all programmers?), but I would expect a function like that to be a part of a modern language. Yes, it didn't take me long to google it (unlike some other C++ problems, which can take hours), but no googling is faster than short googling, isn't it?
I think it is worth seeing, what The Others offer
Labels: Programming

