Suppose we have three double values. We need to format and print them as follows.
We need to print the integer part of the first value in lowercase hexadecimal format.
We need to print the second value to two decimal places and prepend it with a sign to show whether it is positive or negative. The second value to be printed must be right-justified, 15 characters long, and underlined in unused positions on the left.
We need to print the third value in scientific notation with nine decimal places.
So if the input is 256.367, 5783.489, 12.5643295643, the output will be
0x100 _______+5783.49 1.256432956E+01
To solve this problem, we will follow the following steps:
The hex flag prints the value in hexadecimal format, the showbase flag displays the prefix '0x' for the hexadecimal value, the left flag inserts a fill character in the output field to pad the value to the right, The nouppercase flag is printed in lowercase letters.
right flag inserts fill characters in the output field to pad the value to the left, fixed flag prints the value in fixed-point notation, set(15) sets the output field length to 15, The showpos flag inserts a ' ' symbol before the output, setfill('_') fills the output with underscores, and setprecision() sets the precision of the value to 2 decimal places.
setprecision() sets the precision of the value to 9 decimal places, the scientific flag prints the value in scientific notation, uppercase makes the output value uppercase, and noshowpos omits anything before the output value Positive sign.
Let us see the implementation below for better understanding:
#include <iostream> #include <iomanip> using namespace std; void solve(double a, double b, double c) { cout << hex << showbase << nouppercase << left << (long long) a << endl; cout << right << fixed << setw(15) << setfill('_') << setprecision(2) << showpos << b << endl; cout << setprecision(9) << scientific << uppercase << noshowpos << c << endl; } int main() { solve(256.367, 5783.489, 12.5643295643); return 0; }
256.367, 5783.489, 12.5643295643
0x100 _______+5783.49 1.256432956E+01
The above is the detailed content of C++ program to print values in specified format. For more information, please follow other related articles on the PHP Chinese website!