C++如何输出指定的小数位数


C++使用setprecision()函数,同时必须包含头文件iomanip

法一: 

cout.setf(ios::fixed); 
cout<<setprecision(2)<<a<<endl; 
cout.unsetf(ios::fixed); 
法二: 
cout<<fixed; 
cout<<setprecision(2)<<a<<endl; 
cout.unsetf(ios::fixed);
 
测试代码:
 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 int main() {
 5 double a=1/2.0;
 6 double b=1;
 7 //法一
 8 cout.setf(ios::fixed); 
 9 cout<<setprecision(5)<<a<<endl; 
10 cout.unsetf(ios::fixed); //用于取消格式,否则后续输出的小数也会保留5位 
11 //法二 
12 cout<<fixed; 
13 cout<<setprecision(5)<<a<<endl; 
14 cout.unsetf(ios::fixed);
15 return 0;
16 
17 }
View Code

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM