printf
使用格式控制符 %.3f 即可保留三位小数:
#include <bits/stdc++.h>
using namespace std;
// 输入两个整数 a, b, 输出 a 除以 b 的值,保留三位小数
void solve()
{
    int a, b;
    cin >> a >> b;
    printf("%.3f\n", (double)a / b);
}
signed main()
{
    ios::sync_with_stdio(false);
    int t;
    // cin >> t;
    t = 1;
    while (t--)
        solve();
    return 0;
}
cout
使用 fixed 和 setprecision(3) 即可保留三位小数:
#include <bits/stdc++.h>
using namespace std;
// 输入两个整数 a, b, 输出 a 除以 b 的值,保留三位小数
void solve()
{
    int a, b;
    cin >> a >> b;
    cout << fixed << setprecision(3) << (double)a / b << endl;
}
signed main()
{
    ios::sync_with_stdio(false);
    int t;
    // cin >> t;
    t = 1;
    while (t--)
        solve();
    return 0;
}
需要注意的是,如果不使用 fixed,则 setprecision 设置的是有效数字的位数,而不是小数点后的位数。
并且,fixed 和 setprecision 的作用域是全局的,即一旦使用,后续的所有输出都会受到影响。

 京公网安备 11010502036488号
京公网安备 11010502036488号