This example program was created with the sole purpose of showing what setprecision and setw does. I dont understand the purpose of the third line that says "setprecision(5)". I commented the line out to see the difference but it looks the exact same. Is there no purpose?
cout << "\nSales Figures\n";
cout << "-------------\n";
cout << setprecision(5);
cout << "Day 1: " << setw(8) << day1 << endl;
cout << "Day 2: " << setw(8) << day2 << endl;
cout << "Day 3: " << setw(8) << day3 << endl;
cout << "Total: " << setw(8) << total << endl;
The
setprecision()function is part of the "iomanip" library and is used when you need to output a float to a certain number of decimal places. This is good for displaying money amounts and other things that typically are shown with a set number of digits after the decimal point (even if those digits are 0).Say you have a float called price: If you stored 10.0 in that float, C++ would not know how many decimal points to output when you print into the screen;
setprecision(2)would make the output 10.00.You can find the documentation at this link: https://cplusplus.com/reference/iomanip/setprecision/.
It includes the following code as an example of how
setprecision()works.Note that
setprecision()is only applicable to data types with decimal points such as floats and doubles.