C语言中输出时怎样控制小数点后的位数,请举例说明保留1、2、3、4位小数等等,谢谢

如题所述

第1个回答  2022-12-11

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

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

[cpp] view plain copy

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

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

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

    [cpp] view plain copy

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

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

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

    [cpp] view plain copy

    cout.setf(ios::fixed);  

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

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

    [cpp] view plain copy

    cout.unsetf(ios::fixed);  

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

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

    参考代码

    [cpp] view plain copy

    #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;  

    }  

相似回答