小言_互联网的博客

c++保留小数

296人阅读  评论(0)

注意;double cc = 15/6;  为2

(double)sum4 / sum44 这样才行

 

在C++的编程中,总会遇到浮点数的处理,有的时候,我们只需要保留2位小数作为输出的结果,这时候,问题来了,怎样才能让cout输出指定的小数点后保留位数呢?

在C语言的编程中,我们可以这样实现它:

printf("%.2f", sample);

在C++中,是没有格式符的,我们可以通过使用setprecision()函数来实现这个需求。

想要使用setprecision()函数,必须包含头文件#include <iomanip>。使用方式如下:

cout << "a=" << setprecision(2) << a <<endl;

这时候,我们会发现,如果a的值为0.20001,输出的结果为a=0.2,后面第二位的0被省略了。

如果我们想要让它自动补0,需要在cout之前进行补0的定义。代码如下:


 
  1.  

  2. cout.setf(ios::fixed);
    
    cout << "a=" <<fixed<< setprecision(2) << a <<endl; //输出a=0.20

     


 

这样,我们就可以得到0.20了。当然,如果想要关闭掉补0,只需要对fixed进行取消设置操作。


 
  1.  

    cout.unsetf(ios::fixed);

  2.  

    cout << "a=" << setprecision(2) << a <<endl; //输出a=0.2


 

 

我们的输出结果就又变回a=0.2了。

#include <iostream>
 
#include <iomanip>
 
using namespace std;
 
int main()
 
{
 
    float a = 0.20001;
 
    cout.setf(ios::fixed);
 
    cout << "a=" <<fixed<< setprecision(2) << a <<endl; //输出结果为a=0.20
 
    cout.unsetf(ios::fixed);
 
    cout << "a=" << setprecision(2) << a <<endl; //输出结果为a=0.2
 
    return 0;
 
}

 


转载:https://blog.csdn.net/qq_32175379/article/details/102063883
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场