C ++中setprecision的行为 [英] Behaviour of setprecision in C++

查看:60
本文介绍了C ++中setprecision的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double x = 3.14159;

	double y = 131.14159;

	double z = .00314159;

	double a = 13114.159;


	cout << setprecision(3) << "x =  " << x << endl;

	cout << "y =  " << y << endl;

	cout  << "z =  " << z << endl;

	cout  << "a =  " << a << endl;





我尝试过:



我对setprecision的行为有点困惑。据我所知,setprecision试图根据精度值获取小数点前后的最高有效位数(包括在内)。根据我的理解,对于变量z,它输出.00314因为314是3个最有效数字。我不明白为什么最后一个变量输出为1.31e + 04?



What I have tried:

I am little bit confused about the behavior of setprecision. What I understand that setprecision tries to get the most significant digits before and after the decimal point (included) according to the value of precision. From my understanding,for the variable z it outputs .00314 because 314 are 3 most significant digits.I do not understand why for the last variable it outputs as 1.31e+04?

推荐答案

简短的回答是1.31e + 04只是用3位精度表示该数字的唯一方法。 13100会产生误导 - 尾随零可能很重要。 .00314中的前导零明显不重要。
The short answer is that 1.31e+04 is just about the only way to express that number with 3 digits precision. 13100 would be misleading - the trailing zeroes might be significant. The leading zeroes in .00314 are clearly not significant.


这篇关于C ++中setprecision的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆