C++ float,double输出比较
float 类型(单精度浮点类型)
在内存中占用 4 个字节
表示范围:-3.4*1038~+3.4*1038
精度:最长 7 位有效数字(是指 7 位 10 进制位)
float y = 1.123456789;
//精度只能取值到 1.1234568, 在第 8 位(整数部分不算)是四舍五入后的值
注:有效数字指的是从左到右第一位不为0 的数
double 类型(双精度浮点类型)
在内存中占8 个字节
表示范围:-1.7*10308~1.7*10308
精度:最长 16 位有效数字(是指 16 位 10 进制位)
注:在超过第16位的时候,后续不是四舍五入,是无效数据
基本函数使用:
精度设置函数:cout.precision(7);
将精度设置为小数点后精度:cout.flags(cout.fixed);
去除小数点后的精度:** cout.unsetf(cout.fixed);
具体使用见下面代码
#include<iostream>
#include<Windows.h>
using namespace std;
int main(void) {
float float_exam1 = 211.234567890123456789;
double float_exam2 =2111.2345678901256789;
//默认精度6
cout << "默认精度:" << endl;
cout <<"float:" << float_exam1 << endl;
cout << "double:" << float_exam2 << endl;
//精度为5后
cout.precision(7);
cout << "精度设置为18后:" << endl;
cout << "float:" << float_exam1 << endl;
cout << "double:" << float_exam2 << endl;
//小数点后精度为5 cout.flags(cout.fixed)
//注意float的话,有效数字总共7位,小数点后的精度还得考虑小数点前的
cout.flags(cout.fixed);
cout << "小数点后精度为5:" << endl;
cout << "float:" << float_exam1 << endl;
cout << "double:" << float_exam2 << endl;
// 去除小数点后的精度 cout.unsetf(cout.fixed)
cout.unsetf(cout.fixed);
cout << "去除小数点后的精度:" << endl;
cout << "float:" << float_exam1 << endl;
cout << "double:" << float_exam2 << endl;
system("pause");
return 0;
}
运行结果: