I have a 2d array which stores numbers for Maths and Chemistry for X number of sets. Below is how I take input for each class and store them in 2d array for each class.
Input for Maths class:
50 20 30 40 50
Input for Chemistry class:
90 70 20 10 40
Once I take above input for Math and Chemistry class, I need to print like this in below format which will have data for point 1 and 2 above along with the input-
1 2 3 4 5
*****************************
Math 50.00 20.00 30.00 40.00 50.00
Chemistry 90.00 70.00 20.00 10.00 40.00
Problem Statement
I am able to do all above things and calculate point 1 and 2 easily but I am not able to figure out on how to print output in the above format which can show input and ouput in properly formatted way. As of now my program prints everything separately along with the output in different line after taking input -
int main()
{
double val[2][5];
//.. val array being populated
return 0;
}
How can I use cout.setf(ios::fixed)
, cout.setf(ios::showpoint)
and cout.precision(2)
and cout.width(4);
in my above code to get the formatting I need?
This could be a way:
auto w = std::setw(6); // for number like " 10.00" (6 chars)
auto wb = std::setw(8); // for the numbers with more space between them
auto sw = std::setw(11); // for titles (math, chemistry)
// print the numbers above
cout << " ";
for(int i=1; i<=5; ++i) std::cout << w << i;
std::cout << " BEST WORST AVERAGE\n";
// print a line of *
std::cout << sw << "" << std::string(56,'*') << '\n';
cout << std::setprecision(2) << std::fixed; // precision 2, fixed
cout << sw << std::left << "Math" << std::right;
for(auto ms : array[0]) std::cout << w << ms;
cout << wb << math_best << wb << math_worse << wb << math_average << '\n';
cout << sw << std::left << "Chemistry" << std::right;
for(auto cs : array[1]) std::cout << w << cs;
cout << wb << chemistry_best << wb << chemistry_worse << wb << chemistry_average << '\n';
Output
1 2 3 4 5 BEST WORST AVERAGE
********************************************************
Math 50.00 20.00 30.00 40.00 50.00 50.00 20.00 38.00
Chemistry 90.00 70.00 20.00 10.00 40.00 90.00 10.00 46.00
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.