我的理解是,如果不特别说明,一般输出的时候,对于float就是给出6位,但是实际上可以正确输出的是7位,这个可以具体设置。给你一段参考代码,自己试试看:
The following program shows cout truncating to 6 digits:
#include <iostream>
int main() {
using namespace std;
float fValue;
fValue = 1.222222222222222f;
cout << fValue << endl;
fValue = 111.22222222222222f;
cout << fValue << endl;
fValue = 111111.222222222222f;
cout << fValue << endl; }
This program outputs:
1.22222
111.222
111111
Note that each of these is only 6 digits.
However, we can override the default precision that cout shows by using the setprecision() function that is defined in a header file called iomanip.
#include <iostream>
#include <iomanip> // for setprecision()
int main() {
using namespace std;
cout << setprecision(16); // show 16 digits
float fValue = 3.33333333333333333333333333333333333333f;
cout << fValue << endl;
double dValue = 3.3333333333333333333333333333333333333;
cout << dValue << endl;
Outputs:
3.333333253860474
3.333333333333334
Because we set the precision to 16 digits, each of the above numbers has 16 digits. But, as you can see, the numbers certainly aren’t precise to 16 digits!
Variables of type float typically have a precision of about 7 significant digits (which is why everything after that many digits in our answer above is junk). Variables of type double typically have a precision of about 16 significant digits. Variables of type double are named so because they offer approximately double the precision of a float.
追问1.22222
111.222
111111这些都是6位
但3.333333253860474又是7位==>怎么不一致呢?
3.333333333333334作为double又是低位15而不是16?
你的这个是C++吧,我现在刚刚学C语言,两个一样吗?