fixed使用定点计数法什么意思?
#include <iostream>
using namespace std;
int main()
{
float y=3.56000f;
cout.precision(0);
cout.unsetf(ios_base::showpoint);
cout<<"y:"<<fixed<<y<<endl;
system("pause");
return 0;
}
运行结果:4
cout<<"y:"<<fixed<<y<<endl;这句中的fixed是什么意思?
我把fixed去了这后结果是:3.56
看解释说这个是使用定点计数法?什么意思?
[解决办法]
按有效位输出是 setprecision,按小数位数输出也是setprecision,但到底是谁取决于fixed。
cout << resetiosflags(ios::fixed) << setprecision(n) << float-point-number; 是按n位有效数输出
cout << setiosflags(ios::fixed) << setprecision(n) << float-point-number; 是按n位小数输出
看了这个应该能明白
测试代码:
- C/C++ code
#include <iostream>#include <iomanip>using namespace std;int main( void ){ const double value = 12.3456789; cout << value << endl; // 默认以6精度,所以输出为 12.3457 cout << setprecision(4) << value << endl; // 改成4精度,所以输出为12.35 cout << setprecision(8) << value << endl; // 改成8精度,所以输出为12.345679 cout << fixed << setprecision(4) << value << endl; // 加了fixed意味着是固定点方式显示,所以这里的精度指的是小数位,输出为12.3457 cout << value << endl; // fixed和setprecision的作用还在,依然显示12.3457 cout.unsetf( ios::fixed ); // 去掉了fixed,所以精度恢复成整个数值的有效位数,显示为12.35 cout << value << endl; cout.precision( 6 ); // 恢复成原来的样子,输出为12.3457 cout << value << endl;}