Fixed

When I use fixed, it does affect all other operations after it. Why? And how to have (fixed) just affecting the line 10 I'm targeting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream> 
#include <iomanip>
using namespace std;

int main()
{
    cout << "\nDisplay arithmetic operations with mixed data type : " << endl;
    cout << "-------------------------------------------------" << endl;

    cout << "5 + 7 = " << 5 + 7 << endl;
    cout << "3.7 + 8.0 = " << 3.7 + 8.0 << endl;
    cout << "5 + 8.0 = " << fixed << setprecision(1) << 5 + 8.0 << endl; //line I'm targeting
    cout << "5 - 7 = " << 5 - 7 << endl;
    cout << "3.7 - 8.0 = " << 3.7 - 8.0 << endl;
    cout << "5 - 8.0 = " << 5 - 8.0 << endl;
    cout << "5 * 7 = " << 5 * 7 << endl;
    cout << "3.7 * 8.0 = " << 3.7 * 8.0 << endl;
    cout << "5 * 8.0 = " << 5 * 8.0 << endl;
    cout << "5 / 7 = " << 5 / 7 << endl;
    cout << "3.7 / 8.0 = " << 3.7 / 8.0 << endl;
    cout << "5 / 8.0 = " << 5 / 8.0 << endl;

    return 0;
}
Why?

Because that's how it works.

And how to have (fixed) just affecting the line 10

Set it to defaultfloat.
https://en.cppreference.com/w/cpp/io/manip/fixed

 
cout << "5 + 8.0 = " << fixed << setprecision(1) << 5 + 8.0 << defaultfloat << setprecision(6) << '\n';

Last edited on
Why the
setprecision(6) ?
Otherwise it will stay at 1. 6 is the default.
I believe only the width (setw) is automatically reset.
The precision and the flags (e.g., fixed, hex, uppercase, etc.) stay set.
Topic archived. No new replies allowed.