width and precision

I am calculating average and got it working how I like it, but I would like to know how to make the program output with width and a precision

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

int main()
{
    cout << "Enter how many values you want to add: ";
    int items;
    cin >> items;
    double num;
    double sum;
    sum = 0.0;
    for (int x = 1; x <= items; x++)
    {
        cout << "#" << x << " = ";
        cin >> num;
        sum += num;        // equal to sum = sum + num
    }
    cout << "Items = " << items << "\nSum = " << sum << "\nAverage = " << sum / items << "\n";
    
    system("pause");
    return 0;
}
Last edited on
You should check the manipulators setprecision() and setw() provided by the header iomanip.h
Last edited on
Am I using the manipulators correctly?

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
28
29
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    
    cout << "Enter how many values you want to add: ";
    int items;
    cin >> items;
    double num;
    double sum;
    sum = 0.0;
    for (int x = 1; x <= items; x++)
    {
        cout << "#" << x << " = ";
        cin >> num;
        sum += num;        // equal to sum = sum + num
    }
    cout << "Items = " << items << "\nSum = " << sum << "\nAverage = " << sum / items << "\n";
    cout << setprecision (8) << sum << endl;
    cout << fixed;
    cout << setw (12) << sum << endl;
    
    
    system("pause");
    return 0;
}
Last edited on
Topic archived. No new replies allowed.