C++ float,double输出比较

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;
}

运行结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值