IT虾米网

C++保留两位小数的四种方法

xmjava 2023年04月25日 程序员 8373 0

1. 使用iomanip头文件中的setprecision函数

可以使用iomanip头文件中的setprecision函数来设置输出流中的小数位数。例如:

c++ 
#include 
  
    
#include 
   
     
 
using namespace std; 
 
int main() 
{ 
    double num = 3.1415926; 
    cout << setprecision(2) << fixed << num << endl; 
    return 0; 
} 

   
  

输出结果为:3.14

2. 使用printf函数

可以使用printf函数来设置输出流中的小数位数。例如:

c++ 
#include 
  
    
 
int main() 
{ 
    double num = 3.1415926; 
    printf("%.2f\n", num); 
    return 0; 
} 

  

输出结果为:3.14

3. 使用stringstream类

可以使用stringstream类来将double类型的数转换为字符串,并设置小数位数。例如:

c++ 
#include 
  
    
#include 
   
     
#include 
    
      
 
using namespace std; 
 
int main() 
{ 
    double num = 3.1415926; 
    stringstream ss; 
    ss << fixed << setprecision(2) << num; 
    string str = ss.str(); 
    cout << str << endl; 
    return 0; 
} 

    
   
  

输出结果为:3.14

4. 使用自定义函数

可以自定义一个函数来保留小数位数。例如:

c++ 
#include 
  
    
#include 
   
     
 
using namespace std; 
 
double round(double num, int precision) 
{ 
    double factor = pow(10, precision); 
    return round(num * factor) / factor; 
} 
 
int main() 
{ 
    double num = 3.1415926; 
    cout << round(num, 2) << endl; 
    return 0; 
} 

   
  

输出结果为:3.14


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!