作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [问题] 请大家看看
时间Wed Oct 10 00:03:52 2007
※ 引述《popo4231 (小泰)》之铭言:
: #include<iostream>
: using namespace std;
: #include<iomanip>
: using namespace std;
: int main()
: {
: double d = 1.234567891234;
: cout<<fixed<<setprecision(16)<<d<<endl;
: system("pause");
: return 0;
: }
: 输出:1.2345678912339999
: 请按任意键继续 . . .
: 为什麽会这样呢?
: 如果改成showpoint:
: #include<iostream>
: using namespace std;
: #include<iomanip>
: using namespace std;
: int main()
: {
: double d = 1.234567891234;
: cout<<showpoint<<setprecision(16)<<d<<endl;
: system("pause");
: return 0;
: }
: 输出:
: 1.234567891234000
: 请按任意键继续 . . .
: 超奇怪的
: 可以帮忙解答吗
The key points are (1) the precision issue of floating number in computer,
and (2) the definition of "setprecision()".
(1) As I mentioned in the class, floating numbers ARE not always precise when
represented in computer, mainly due to the limited bits of representation.
The FLT_EPSILON = 1.19209e-07, and DBL_EPSILON = 2.22045e-16. So the number
1.234567891234 is actually stored as 1.234567891233999903377593909681...
in computer.
(2) The definition of "setprecision()". Let me quote from cpluplus.com:
==========================================================================
The decimal precision determines the maximum number of digits to be written
on insertion operations to express floating-point values. How this is
interpreted depends on whether the floatfield format flag is set to a
specific notation (either fixed or scientific) or it is unset (using the
default notation, which is neither fixed nor scientific):
On the
default floating-point notation, the precision field specifies the
maximum number of meaningful digits to display in total counting both those
before and those after the decimal point. Notice that it is not a minimum and
therefore it does not pad the displayed number with trailing zeros if the
number can be displayed with less digits than the precision.
In both the
fixed and
scientific notations, the precision field specifies
exactly how many digits to display after the decimal point, even if this
includes trailing decimal zeros. The number of digits before the decimal
point does not matter in this case.
==========================================================================
In short, the statement
cout<<showpoint<<setprecision(16)<<d<<endl;
will print out totally 16 digits from the number. So ---
d = 1.234567891233999903377593909681
= 1.234567891234000
where it rounds at the 15th digit after the decimal point.
However, the statement
cout<<fixed<<setprecision(16)<<d<<endl;
will print out 16 digits AFTER the decimal point. So ---
d = 1.234567891233999903377593909681
= 1.2345678912339999
because the 17th digit after decimal point is 0.
Note:
If you try "setprecision(17)", you will see consistent numbers.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.121.131.190
※ 编辑: ric2k1 来自: 59.121.131.190 (10/10 00:08)
1F:→ ric2k1:刚刚 showpoint, fixed 写反了... 10/10 00:08