浮点型精度控制方法--C++

结论:2种写法

int main(){
    const double d = 12.345678901234;
    // 1.precision(val)
    cout.precision(2);
    cout<<d<<endl;
    cout<<fixed<<d<<endl;

    // 2.setprecision(val)
    cout<<fixed<<setprecision(3)<<d<<endl;
}

output:
12
12.35
12.346

  解释

        precision

        作用:

        1.返回当前精度                                                                         precision()

        2. 将精度设置为给定的精度(数字的长度)。返回之前的精度。 precision(new_precision)

        作用于全局。

         例子:

int main()
{
    const double d = 12.345678901234;
    cout << std::cout.precision() << "\n\n";
    cout << d << '\n';
    cout.precision(8);
    cout << d << '\n';
}

output:
6
12.3457
12.345679
       
         setprecision

        作用:

       作用与precision()相同。

        作用于全局。

        例子: 

int main(){
    double d=12.24324;
    cout<<setprecision(2)<<d<<endl;
    cout<<setprecision(3)<<d<<endl;
}

output:
12
12.2

        fixed

        作用:

实现无科学记数法的小数点后6位。

与precision()/setprecision()配合,可将其变为控制小数点后需要输出的位数。

作用于全局。

         例子:

int main(){
    double d=0.000000024324123243454564;
    cout<<d<<endl;
    cout<<fixed<<d<<endl;
    cout.precision(8);
    cout<<d<<endl;
}

output:
2.43241e-08
0.000000
0.00000002

参考:

详解C++中fixed,setprecision(),setw()的用法_c++ fixed-优快云博客

precision参数,返回值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cando-01

随心而动,随性而为。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值