✔ 最佳答案
"Paul" I tried to use function round(double) <math.h> but I still get "undeclared identifier" error!!! do you know why???
I wrote this function:
float round(const float &number, unsigned int precision=(unsigned int)3)
{
if(precision>6)
precision = 3; // set Default
if(number>0.0)
{
// holds the integer value of 'number'
int integer = (int)floor(number);
// holds the decimal value of 'number'
int decimal = (number-integer) * pow(10,(double)precision);
// truncate decimal value with respect to 'precision'
float truncated = ((float)decimal) / (float)pow(10,(double)precision);
// holds the last digit of the decimal value
int ldigit = decimal % 10;
if(ldigit>=5 && precision==1)
{
integer += 1;
return static_cast<float>(integer);
}
else if(ldigit>=5)
decimal += 10 - ldigit; // round
else
decimal /= 10; // truncate
truncated = ((float)decimal) / (float)pow(10,(double)precision); // update
return static_cast<float>(integer) + truncated;
}
return number;
}
Another function to round double number and more precise:
http://stackoverflow.com/questions/554204/where-is-round-in-c
#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;
}