Setprecision is not working right ?

Jan 19, 2019 at 7:24pm
I hope I don't need to translate the whole code but the thing is for the first meters even tho I use setprecision(2) I get more numbers after the comma "1 meter = 39.3701 coliu. (Should be 39.37)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
//
const char duom [] = "duomenys.txt";
const char rez [] = "r.txt";
//
int main()
{
    ifstream fd(duom);
    ofstream fr(rez);
    int n, m;
    float colis = 2.54, peda = 12, jardas = 3; // 1 colis = 2.54cm, 3 pedos = 1 jardas, 12 coliu = 1 peda
    float col = 0, ped = 0, jard = 0;
    fd >> n;
    for (int i = 1; i <= n; i++){
        fd >> m;
        m *= 100; // verciu centimetrais
        col = m / colis;
        ped = col / peda;
        jard = ped / jardas;
        fr << i << " sudaro: " << col << fixed << setprecision(2) << " coliu." << endl;
    }
    return 0;
}
Jan 19, 2019 at 7:38pm
Put this before the loop. It only needs to be done once.

 
fr << fixed << setprecision(2);

Jan 19, 2019 at 7:44pm
Thank you but could you give the full reason why it doesn't work in the loop?
Jan 19, 2019 at 7:51pm
It needs to be done before you print the floating point number col, but you did it after.
Topic archived. No new replies allowed.