The following code snippet calculates the average of 3 numbers.
The
setprecision()
setprecision()
function in C++ is used to set the number of digits displayed for floating-point numbers when outputting with streams likecout
. 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, usingsetprecision(4)
would format the output to show a total of four digits, including those before and after the decimal point.
#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
#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.float a, b, c, avg;
a = 14;
b = 8;
c = 16;
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.avg = (a + b + c) / 3;
a
, b
, and c
. The sum of these three variables is divided by 3 to obtain the mean, which is then stored in avg
.cout << "Average of " << a << ", " << b << " and " << c << " is: " << setprecision(4) << avg << endl;
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.