关于精度宽度设置
来源:互联网 发布:砸金蛋抽奖软件 编辑:程序博客网 时间:2024/05/16 18:04
C++的输出格式控制,主要是需要<iomanip>这个头文件。(旧式的C++采用<iomanip.h>。顺便说一句,您应该写#include <iostream>,然后用using namespace std;,
对于浮点数输出来讲,主要需要了解的是三个概念:
(1) 浮点数有三种输出方式。第一种是普通计数法,第二种是科学计数法,第三种是从普通计数法和科学计数法两者选较短的一个为准。默认是第三种方式输出。
(2) 输出宽度。如果指定了宽度,并且输出的字符数没有达到指定宽度,则会用一些字符去填充,默认用空格填充。
(3) 输出精度(这个就是您现在最应该关心的)。对于普通计数法,输出精度就是小数位数。对于科学计数法,输出精度就是有效数字位数。
cout << resetiosflags(ios::floatfield) << setw(20) << setiosflags(ios::fixed) << setprecision(3) << -2.77556e-16 << endl;
cout << resetiosflags(ios::floatfield) << setw(20) << setiosflags(ios::scientific) << setprecision(3) << -2.77556e-16 << endl;
输出:
3.1416
3.14159
3.14159
3.141590000
-0.000
-2.776e-016
请按任意键继续. . .
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main( void )
{
const double value = 12.3456789;
//无论是有fixed的对小数位数的设置,还是直接对数位的设置都会牵扯到一个四舍五入
cout << value << endl; // 默认以6精度,所以输出为 12.3457,此精度表示的是整个value值的位数是6位
cout << setprecision(4) << value << endl; // 改成4精度,所以输出为12.35
cout << setprecision(8) << value << endl; // 改成8精度,所以输出为12.345679 注意默认和直接set精度都是值整个数的位数,
cout << fixed << setprecision(4) << value << endl; // 加了fixed意味着是固定点方式显示,所以这里的精度指的是小数位,输出为12.3457
cout << value << endl; // fixed和setprecision的作用还在,依然显示12.3457
cout.unsetf( ios::fixed ); // 去掉了fixed, 仅仅去掉了一个fixed的作用,set的作用依然存在,所以精度恢复成整个数值的有效位数,显示为12.35
cout << value << endl;
cout.precision( 6 ); // 恢复成原来的样子,输出为12.3457
cout << value << endl;
cout<<fixed<<value<<endl;
system("pause");
return 0;
}
1、简介
函数原型:
template<class Elem>
T4 setfill(
Elem _Ch
);
功能:
在预设宽度(setw)中如果已存在没用完的宽度大小,则用设置的字符填充
参数:
Elem _Ch, 用来被填充的字符
返回值:
The template manipulator returns an object that, when extracted from or inserted into the stream str, calls str.fill(_Ch), and then returns str. The type Elem must be the same as the element type for the stream str.
要求:
Header: <iomanip>
Namespace: std
2、范例
#include <iomanip>
#include <iostream>
void main()
{
std::cout << std::setfill('#') << std::setw(5) << "1" << std::endl;
std::cout << std::setfill('#') << std::setw(5) << "10" << std::endl;
std::cout << std::setfill('#') << std::setw(5) << "100" << std::endl;
std::cout << std::setfill('#') << std::setw(5) << "1000" << std::endl;
}
//
// 输出结果:
// ####1
// ###10
// ##100
// #1000
- 关于精度宽度设置
- 关于对话框无法设置宽度
- 关于table设置固定宽度高度自适应
- 关于Easyui region 设置高度和宽度
- 关于精度
- 字段宽度和精度使用
- 关于CDockablePane不能设置固定宽度的解决方案
- 关于Android GridLayou 的孩子控件宽度设置,超出屏幕
- 关于在 UITableView FooterView 中控件宽度设置问题
- 关于span标签的宽度和高度设置
- 关于自定义dialog动态设置宽度没有效果问题
- c++ cout 控制精度、宽度、进制
- 指定宽度和精度的例子
- printf宽度控制和精度控制
- cout设置输出精度
- java 设置小数点精度
- 小数精度设置
- Maltab 坐标轴精度设置
- singular value decomposition----SVD
- 进程关系之进程组、会话和控制终端
- matlab练习程序(SUSAN检测)
- python列表排序
- Serializable初次学习
- 关于精度宽度设置
- Hdu 1754——I Hate It
- python os模块,平常操作文件方便,执行cmd命令
- 求1-N内的素数
- xcode: valid signing identity not found
- linux chmod命令
- 黑马程序员——反射机制
- 面向对象(购买电脑)
- windows + visual studio 2010 配置SVN