68.7k views
2 votes
Write a cout statement so that the variable totalAge is displayed in a field of 12 spaces, in fixed point notation, with a precision of 4 decimal places.

User Tetrinity
by
5.0k points

1 Answer

5 votes

Answer:

The syntax is as follows.

cout<<setw(12)<<totalAge<<setprecision(4)<<endl;

Step-by-step explanation:

The header files needed for the formatting mentioned in the question are iostream and iomanip.

The iostream file is used for basic input and output operations using cout and cin.

The iomanip file is used because it contains both setw() and setprecision() methods. This method is used to set the width of the space needed to display the output.

The parameter needed for setw() method is a number.

As given in the question statement, we need the field to be 12 spaces wide to display the value of the floating point variable, totalAge.

The setw(12) method tells the compiler to keep aside the field of 12 spaces or 12 characters wide.

The count of decimal numbers to be displayed after the decimal can be fixed by using the setprecision() method. This method tells the compiler to display the decimal number with the required number of numbers after the decimal.

The setprecision() takes a numerical parameter. This number decides the count of numbers that should be displayed after the decimal.

In this question, totalAge is to be displayed with 4 decimal places hence, the method will be written as setprecision(4).

The c++ program which uses the above cout statement is shown.

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

double totalAge = 52.123456;

cout<<"Total age is "<<endl;

cout<<setw(12)<<totalAge<<setprecision(4)<<endl;

return 0;

}

OUTPUT

Total age is

52.1235

Total space needed to display the message is also 12 spaces long including spaces.

Total age is

The variable is displayed beginning from the right side of the space. The question asks to display the number with 4 decimal places hence, the value of the variable is taken to show the working.

The value of totalAge is first rounded up and then displayed with 4 decimal places.

User Sahil Grover
by
4.5k points