关于setprecision(n)的问题
来源:互联网 发布:ubuntu 一键openstack 编辑:程序博客网 时间:2024/06/05 04:09
关于setprecision(n)的问题
例1
// setprecision example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
double f =3.14159;
cout << setprecision (5) << f << endl;
cout << setprecision (9) << f << endl;
return 0;
}
输出:
若将以上代码中f设置为double f=0.14159,则结果如下:
结论1:setprecision设置浮点数从左起第一个不为零的数位开始计算到右边最后一个不为零的数位为止的有效数位的位数的最大值,并且进行四舍五入。
例2:
#include "ostream.h"
#include "istream.h"
#include "iomanip.h"
void main()
{
double amount=22.0/7; // 3.142857 142857 14285714
cout<<amount<<endl; //第一行
cout<<setprecision(0)<<amount<<endl //第二行
<<setprecision(1)<<amount<<endl //第三行
<<setprecision(2)<<amount<<endl; //第四行
}
输出:
分析:
第一行的输出数值之前没有设置有效位数,所以用流的有效位数默认设置值6;
第二行输出有效位数0,C++最小的有效位数为1,所以作为有效位数设置为1来看待;
第三行输出有效位数为1;
第四行输出有效位数为2,并四舍五入;
注意:对于第三行,有些人得出的输出如下:
他们给出的根据和理同如下:
MDSN上的解释: If the display format is scientific or fixed, then the precision indicates the number of digits after the decimal point. If the format is automatic (neither floating point nor fixed), then the precision indicates the total number of significant digits. This setting remains in effect until the next change. 应该是设置非法参数。
C或C++中当函数的参数非法时,通常默认其参数不起作用!如,
print("%0.2lf/n",je);这个0就不起作用,其整数部分只是照默认的输出!
问:还有的是计算中
好像例如double i=(13/7) //1.857 142857 142857
cout<<setprecision (5)<<i;
他们的结果是7位小数阿
可是我实践的结果却
问:还有
但是我输入了一个
double i=1.00000
然后我
cout<<setprecision (5)<<i;
它输出的是 1。
真得不懂了
这个为什么呢?
答:尾部所带的所有0都不属于有效数位的范畴。
- 关于setprecision(n)的问题
- 关于c++浮点数的数字个数setprecision(n)与setiosflags(ios::fixed)
- fixed<<setprecision(n)
- setw(0)和setprecision(n)的用法 -ZT
- C++最简单的四舍五入!!(setprecision(n)方法)
- C++最简单的四舍五入!!(setprecision(n)方法)
- 关于java的n=n++问题
- 【2001】关于N!的问题
- Setprecision
- setprecision
- setprecision
- 使用setprecision(n)可控制输出流显示浮点数的数字个数
- YTU oj1058: 三角形面积 (C++最简单的四舍五入!!(setprecision(n)方法)
- setprecision(int n)等格式函数用法
- setprecision(int n)等格式函数用法
- 关于n!的位数的问题
- 关于C语言的N皇后问题
- 关于3n+1问题的验证
- 我的心太乱
- [转]Linux 下的线程读写锁 - 空穴来风 - C++博客
- C++ 技术资料(大视野网络收集)
- 为什么“汉编”没搞头
- showModalDialog
- 关于setprecision(n)的问题
- log4j
- “请”的翻译种种
- Singleton 单件(创建型模式)
- 多线程开发,'_beginthreadex' : undeclared identifier
- ASP.NET Process Model之一:IIS 和 ASP.NET ISAPI
- Abstract Factory 抽象工厂模式(创建型模式)
- 你“真了不起”
- 钩子程序