C++以cout方式输出并保留n位小数

在C++中以cout方式输出并保留n位小数,首先需要引入iomanip(input/output manipulator, 输入输出操纵器)头文件。

#include<iomanip>

fixed和setprecision(n)是iomanip中的流操纵器,可用于控制输入/输出流的格式等。一旦设置,格式会持续生效,直到被显式修改或程序结束。

1.仅使用fixed。

输出浮点型数据,默认保留6位小数,四舍五入。

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double x = 3.141592653589793;

    cout << "Default: " << x << endl;          // "3.14159"

    cout << "Fixed: " << fixed << x << endl; // "3.141593"

    return 0;
}

2.仅使用setprecision(n)。

四舍五入保留n位有效数字。

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double a = 3.14159265;
    double b = 12345.6789;
    double c = 0.000123456;

    cout << "a (precision=3): " << setprecision(3) << a << endl;  // "3.14"
    cout << "a (precision=5): " << setprecision(5) << a << endl;  // "3.1416"
    cout << "b (precision=5): " << setprecision(5) << b << endl;  // "12346"
    cout << "c (precision=2): " << setprecision(2) << c << endl;  // "0.00012"

    return 0;
}

3.fixed和setprecision(n)结合使用。

四舍五入保留n位小数。

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double x = 3.141592653589793;

    cout << fixed << setprecision(2) << x << endl; // "3.14"
    cout << fixed << setprecision(4) << x << endl; // "3.1416"

    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值