' P '

whatever I will forget

C++ 小数点n桁を丸めたい時

そんな時は、
#include<iomanip> をインクルードし

coutに
cout << fixed << setprecision(1) をすれば良いだけです。

()の中に該当するのが丸める桁数。
例だと小数点1桁以下を丸める。

#include <iostream>
#include <vector>
#include <iomanip> 

using namespace std;

int main() {

    double total{};
    double avg{};
    
    vector <double> vc {10.1, 20.3, 31.2};
    for (auto v: vc)
        total += v;
    avg = total / vc.size();
    cout << fixed << setprecision(1);
    cout << avg << endl;
    
    return 0;

}

結果は20.5 となります。
前エントリーと同じコードですが、以前は20.5333と表示されていました。