C++数字按指定的位数输出

转载自: http://blog.csdn.net/zy122121cs/article/details/52094352

 

这里探讨C++如何将数据按指定的位数输出,如将所有打印在屏幕上的数据都按4位数输出,不够的前面补0。这里要用到C++的两个输出控制,setw(位数),和setfill(指定字符)。

不讲废话了,见下面代码:

 

[cpp] view plain copy
 
  1. #include <iostream>  
  2. #include <iomanip>//一定要包含这个c++头文件,非常重要  
  3.   
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     int test[4] = { 1, 12, 123, 1234 };  
  9.     for (int i = 0; i < 4; ++i)  
  10.     {  
  11.         cout << setw(4) << setfill('0') << test[i] << " ";  
  12.     }  
  13.     cout << endl << endl;  
  14.     return 0;  
  15. }  


 

 

输出结果如下:


 
posted @ 2018-03-18 21:52  博客园—哆啦A梦  阅读(976)  评论(0)    收藏  举报