Average of 3 numbers (included number rounding)

The following code snippet calculates the average of 3 numbers.

The setprecision() function in C++ is used to set the number of digits displayed for floating-point numbers when outputting with streams like cout. It is defined in the <iomanip> header and modifies the precision of the output stream. The precision affects both the total number of digits displayed for floating-point numbers and how they are rounded. For instance, using setprecision(4) would format the output to show a total of four digits, including those before and after the decimal point.

Code Example

#include <iostream>
#include <iomanip>
using namespace std;

int main () {
    // declare variables
    float a, b, c, avg; 

    // initialize variables
    a = 14;
    b = 8;
    c = 16;
    
    avg = (a + b + c) / 3;

    /* setprecision(n): setting the decimal places and rounding */
    cout << "Average of " << a << ", " << b << " and " << c << " is: " << setprecision(4) << avg << endl;
}

Output

Average of the numbers 14, 8 and 16 is: 12.67

Code Explanation

1. Including Header Files:

#include <iostream>
#include <iomanip>
  • #include <iostream> includes the standard input/output stream library, essential for using input and output streams such as cin and cout.
  • #include <iomanip> brings in the input/output manipulators library, which allows for advanced formatting options like setprecision used to control the number of displayed decimal digits.

2. Variable Declaration and Initialization:

float a, b, c, avg;
a = 14;
b = 8;
c = 16;
  • Here, four floating-point variables are declared: a, b, c, and avg. The variables a, b, and c are immediately assigned the values 14, 8, and 16, respectively, which are the numbers used in the average calculation.

3. Calculate the Average:

avg = (a + b + c) / 3;
  • This line computes the average of the values stored in a, b, and c. The sum of these three variables is divided by 3 to obtain the mean, which is then stored in avg.

4. Output the Result:

cout << "Average of " << a << ", " << b << " and " << c << " is: " << setprecision(4) << avg << endl;
  • The cout is used for printing output to the standard output device (typically the screen). This statement constructs a string that includes the values of a, b, and c, followed by the average formatted to four decimal places using setprecision(4). Finally, endl adds a newline and flushes the buffer, ensuring all output is displayed.