c++ When outputting numbers, it is useful to be able to state how many column po
ID: 3743129 • Letter: C
Question
c++
When outputting numbers, it is useful to be able to state how many column positions the number should occupy. We can do this with another manipulator called setw. This manipulator (available in file ) states how many columns the following data value is to occupy. For example,
prints the contents of intValue right-justified in four columns. The parameter to setw is an integer expression called the fieldwidth. If the fieldwidth is not large enough to contain the digits in the number, it is automatically expanded to the appropriate size. You specify the fieldwidth for floating-point numbers the same way (don't forget to include the decimal point in your fieldwidth count). You can set the number of decimal places to be shown by using the manipulator setprecision (also in file ). For example,
prints 3.142. Note that the last digit printed has been rounded. setprecision(3) remains in effect until the next setprecision is used, whereas setw applies only to the value immediately following.
There are two additional manipulators available in that are useful when working with floating point numbers: fixed and showpoint. fixed forces all subsequent floating point output to be in decimal format, and showpoint forces all subsequent floating point output to show a decimal point even though the values are whole numbers.
PROBLEM 2
Use the following program shell for PROBLEMS 2 through 5.
Write a program to print the following numbers right-justified in a column on the screen. Make the values named constants.
When you are finished, copy and paste your output to the end of your source code as a comment. Re-compile this commented code to make sure that your have not introduced any new errors.
Explanation / Answer
// Program Numbers sends numbers to the output stream in
// specified formats.
/* for doing right justification in a column for numbers other than those
specified in the question the value inside the bracket of the setw command must
be the number of digits of the number with highest digit count.
example:
in 1234, 23, 112, 3, 98763
the number with the maximum number of digits is 98763 with the number of digits equal
to 5. So the setw command should be written as setw(5) in place of setw(4) as
done in the question.*/
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
const int a = 1066, b = 1492, c = 512, d = 1, e = -23;
cout << fixed << showpoint;
cout << std::setw (4)<<a << endl;
cout << std::setw (4)<<b << endl;
cout << std::setw (4)<<c << endl;
cout << std::setw (4)<<d << endl;
cout << std::setw (4)<<e << endl;
return 0;
/* output
1066
1492
512
1
-23
*/
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.