fork download
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. double round(double dValue, int nCount)
  7. {
  8. double dSign = dValue < 0 ? -1 : 1;
  9. double dPow = pow((double)10., nCount); //лучше иметь предвычисленные значения
  10. double eps = 0.001;
  11. return dSign * (floor(fabs(dValue) * dPow + 0.5 + eps) / dPow);
  12. }
  13.  
  14. void test(double v, int c)
  15. {
  16. printf("round(%.15lf, %d) = %.15lf\n", v, c, round(v, c));
  17. }
  18.  
  19. int main()
  20. {
  21. test(4.725, 2);
  22. test(4.724, 2);
  23. test(4.7248, 2);
  24. test(4.7249, 2);
  25. test(4.72498, 2);
  26. test(4.724989, 2);
  27. test(4.7249899999, 2);
  28. test(4.72499, 2);
  29. test(4.724999, 2);
  30. return 0;
  31. }
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
round(4.725000000000000, 2) = 4.730000000000000
round(4.724000000000000, 2) = 4.720000000000000
round(4.724800000000000, 2) = 4.720000000000000
round(4.724900000000000, 2) = 4.720000000000000
round(4.724980000000000, 2) = 4.720000000000000
round(4.724989000000000, 2) = 4.720000000000000
round(4.724989999900000, 2) = 4.720000000000000
round(4.724990000000000, 2) = 4.730000000000000
round(4.724999000000000, 2) = 4.730000000000000