The following code snippet calculates the average of 3 numbers.setprecision()
sets the decimal precision.
Line | Description |
---|---|
7 | Declares the variables a , b , c and avg of type float |
10 – 12 | Initializes the variables a , b and c with the values 14, 8 and 16 |
14 | Calculates the average of variable a , b and c |
17 | Outputs the mean value via the setprecision() function |
#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;
}
Average of the numbers 14, 8 and 16 is: 12.67