C++中关于数据小数点,取整的方法

来源:互联网 发布:图书管理数据库er图 编辑:程序博客网 时间:2024/06/15 18:19

小数位数控制


在遇到要计算浮点数且希望能控制其输出、精度、小数点后的位数等时,而使用cout进行格式输出,可以使用setprecision(n),这个函数是控制从左侧起,第一个不为零的数为有效位,如:

double a = 0.123;double b = 1.233;double c = 0.0125;cout << setptecision(3) << a << " " << b << " " << c << endl;
结果为 0.123 1.23 0.0125

如果需要指定小数点后面的位数,可以使用setiosflags( ios::fixed ),其头文件为:include<iomanip>.
double a = 0.123;double b = 1.233;double c = 0.0125;cout << setiosflags(ios::fixed) << setptecision(3) << a << " " << b << " " << c << endl;
结果为 0.123 1.233 0.012



取整方法

头文件#include <math.h> 

1. 函数doubleceil(double x)
     向下取整
     eg:
     ceil(-11.5) == -11        ceil(1.5)== 1       ceil(-6.2) ==  -6     ceil(6.1)  ==  6

2. 函数 floor(double x)  floorf(float x)  floorl(long double x)
    向上取整
    eg:
floor(-11.5)  == -12       floor(1.5)  == 2    floor(-6.2)  == -7            floor(6.1) == 7

3. 函数round()
    四舍五入
    eg:
round(-11.5)  == -12           round(1.5) == 2              round(-6.2)   == -6               round(6.1)  == 6




0 0
原创粉丝点击