当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ iomanip setpricision()用法及代码示例


C++中的iomaip库的setprecision()方法用于基于为此方法的参数指定的精度来设置ios库浮点精度。

用法:

setprecision(int n)

参数:此方法接受n作为参数,它是要设置浮点精度的整数参数。


返回值:此方法不返回任何内容。它仅充当流操纵器。

示例1:

// C++ code to demonstrate 
// the working of setprecision() function 
  
#include <iomanip> 
#include <ios> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
  
    // Initializing the decimal 
    double num = 3.142857142857; 
  
    cout << "Before setting the precision: \n"
         << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using"
         << " setprecision to 5: \n"
         << setprecision(5); 
  
    cout << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using
            "<<" setprecision to 9 : \n " 
         << setprecision(9); 
  
    cout << num << endl; 
  
    return 0; 
}
输出:
Before setting the precision: 
3.14286
Setting the precision using setprecision to 5: 
3.1429
Setting the precision using setprecision to 9: 
3.14285714

示例2:

// C++ code to demonstrate 
// the working of setprecision() function 
  
#include <iomanip> 
#include <ios> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
  
    // Initializing the decimal 
    double num = 3.14; 
  
    cout << fixed; 
  
    cout << "Before setting the precision: \n"
         << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using"
         << " setprecision to 5: \n"
         << setprecision(5); 
  
    cout << num << endl; 
  
    // Using setprecision() 
    cout << "Setting the precision using"
         << " setprecision to 9: \n"
         << setprecision(9); 
  
    cout << num << endl; 
    return 0; 
}
输出:
Before setting the precision: 
3.140000
Setting the precision using setprecision to 5: 
3.14000
Setting the precision using setprecision to 9: 
3.140000000

参考: http://www.cplusplus.com/reference/iomanip/setprecision/



相关用法


注:本文由纯净天空筛选整理自guptayashgupta53大神的英文原创作品 iomanip setpricision() function in C++ with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。