65,182
社区成员




#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.2f",round(37.975*1e3)/1e3);
return 0;
}
//Round(1.234,2) = 1.23
//Round(1.234,0) = 1.0
//Round(123.4,-1) = 120.0
double Round(double dVal, short iPlaces) {
double dRetval;
double dMod = 0.0000001;
if (dVal<0.0) dMod=-0.0000001;
dRetval=dVal;
dRetval+=(5.0/pow(10.0,iPlaces+1.0));
dRetval*=pow(10.0,iPlaces);
dRetval=floor(dRetval+dMod);
dRetval/=pow(10.0,iPlaces);
return(dRetval);
}
double round(double dVal, short iPlaces) //iPlaces>=0
{
unsigned char s[20];
double dRetval;
sprintf(s,"%.*lf",iPlaces,dVal);
sscanf(s,"%lf",&dRetval);
return (dRetval);
}
#include <stdio.h>
#include <math.h>
double round(double r)
{
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
int main(void)
{
printf("%.2f",round(37.975*1e3)/1e3);
return 0;
}
2.1 2.6 -2.1 -2.6
floor : 不大于自变量的最大整数 2 2 -3 -3
ceil :不小于自变量的最大整数 3 3 -2 -2
round:四舍五入到最邻近的整数 2 3 -2 -3
floor(),ceil() 需包含头文件<math.h>
C++中没有直接的round函数 需自己建立
double round(double r)
{
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
double RoundTo(double N, int Digit)
{
if ((Digit < -37) || (Digit > 37))
return N;
double Factor = pow(10.0, Digit);
if (N < 0)
return floor(N / Factor - 0.5) * Factor;
else
return floor(N / Factor + 0.5) * Factor;
}
用法和大嘴的代码一样。