✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:C/C++知识点
📣专栏定位:整理一下 C++ 相关的知识点,供大家学习参考~
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
🎏唠叨唠叨:在这个专栏里我会整理一些琐碎的 C++ 知识点,方便大家作为字典查询~
浮点数据的输出控制
默认精度
默认情况下,精度是指总的有效数字,且默认精度是 6
double value = 12.3456789;
cout << value << endl;
精度修改
精度修改后,持续有效,直到精度再次被修改
cout.precision(4);
cout << value << endl;
定点法
精度变成小数点后面的位数
cout.flags(cout.fixed);
cout << value << endl;
精度恢复
把精度恢复成有效数字位数
cout.unsetf(cout.fixed);
cout << value << endl; //输出12.35
cout << 3.1415926534 << endl; //输出3.142
全部代码
#include<iostream>
#include<Windows.h>
using namespace std;
int main() {
double value = 12.3456789;
//默认精度是6,所以输出为12.3457
//默认情况下,精度是指总的有效数字
cout << value << endl;
//把精度修改为4,输出12.35,对最后一位四舍五入
//精度修改后,持续有效,直到精度再次被修改
cout.precision(4);
cout << value << endl;
//使用定点法,精度变成小数点后面的位数
//输出12.3457
cout.flags(cout.fixed);
cout << value << endl;
//定点法持续有效
//输出3.1416
cout << 3.1415926534 << endl;
//把精度恢复成有效数字位数
cout.unsetf(cout.fixed);
cout << value << endl; //输出12.35
cout << 3.1415926534 << endl; //输出3.142
system("pause");
return 0;
}