c++ math.h中有这么几种函数:round,floor,ceil,trunc
round提供四舍五入,floor向下取整,ceil向上取整,trunc截断
例子
/* round vs floor vs ceil vs trunc */ #include <stdio.h> /* printf */ #include <math.h> /* round, floor, ceil, trunc */ int main () { const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n"; printf ("value\tround\tfloor\tceil\ttrunc\n"); printf ("-----\t-----\t-----\t----\t-----\n"); printf (format, 2.3,round( 2.3),floor( 2.3),ceil( 2.3),trunc( 2.3)); printf (format, 3.8,round( 3.8),floor( 3.8),ceil( 3.8),trunc( 3.8)); printf (format, 5.5,round( 5.5),floor( 5.5),ceil( 5.5),trunc( 5.5)); printf (format,-2.3,round(-2.3),floor(-2.3),ceil(-2.3),trunc(-2.3)); printf (format,-3.8,round(-3.8),floor(-3.8),ceil(-3.8),trunc(-3.8)); printf (format,-5.5,round(-5.5),floor(-5.5),ceil(-5.5),trunc(-5.5)); return 0; }
Output:
value round floor ceil trunc ----- ----- ----- ---- ----- 2.3 2.0 2.0 3.0 2.0 3.8 4.0 3.0 4.0 3.0 5.5 6.0 5.0 6.0 5.0 -2.3 -2.0 -3.0 -2.0 -2.0 -3.8 -4.0 -4.0 -3.0 -3.0 -5.5 -6.0 -6.0 -5.0 -5.0
关于有效数字问题,保留几位有效数字以及同时要求保留几位小数的实现:需要用到setprecision,用以保留有效数字,加上fixed,用以保留特定几位小数
例子
// setprecision example #include <iostream> // std::cout, std::fixed #include <iomanip> // std::setprecision int main () { double f =3.14159; std::cout << std::setprecision(5) << f << '\n'; std::cout << std::setprecision(9) << f << '\n'; std::cout << std::fixed; std::cout << std::setprecision(5) << f << '\n'; std::cout << std::setprecision(9) << f << '\n'; return 0; }
Output:
3.1416 3.14159 3.14159 3.141590000
同时保留特定几位小数输出
// modify floatfield #include <iostream> // std::cout, std::fixed, std::scientific int main () { double a = 3.1415926534; double b = 2006.0; std::cout.precision(5); std::cout << "default:\n"; std::cout << a << '\n' << b << '\n' << c << '\n'; std::cout << '\n'; std::cout << "fixed:\n" << std::fixed; std::cout << a << '\n' << b << '\n' << c << '\n';
return 0; }
Output:
default: 3.1416 2006 1e-010 fixed: 3.14159 2006.00000 0.00000