Search code examples
c++outputiomanip

Is there a way to format output more specifically in C++?


When I assign the value in setprecision() to 1

and

{ 1, 1, 1, 2, 1, 1, 1, 4, 1, 0, 1, 1 }

is inputted as values, MyProgrammingLab says I have an error in the output for average. My program displays 1.2 when it should display 1.25.

So when I change the value in setprecision() to 2

and

{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }

is inputted as values, MyProgrammingLab says again I have an error in the output for average. My program displays 6.50 when it should only display 6.5.

What can I do so that average is outputted correctly in both instances?

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

   // Creating int variable to hold total 
   double total = 0;

   // Array
   double value[12];

   // Loop to prompt user for each value
   for (int i = 0; i < 12; i++) {
      cout << "Enter value: ";  
      cin >> value[i];
    }

   // Loop to add all values together
   for (int i = 0; i < 12; i++)
       total += value[i];

   // Creating a double to hold average
   double average;

   // Formatting output
   cout << fixed << showpoint << setprecision(2);

   // Calculating average
   average = total / 12;

   // Displaying average
   cout << "Average value: " << average << endl;

   return 0;

}

Solution

  • You could write a little helper function that formats the string the way you want. I've put comments in my code to explain.

    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <sstream>
    
    std::string RemoveTrailingZero(double value)
    {
        //Convert to precision of two digits after decimal point
        std::ostringstream out;
        out << std::fixed << std::setprecision(2) << value;
        std::string str = out.str();
    
        //Remove trailing '0'
        str.erase(str.find_last_not_of('0') + 1, std::string::npos);
    
        //Remove '.' if no digits after it
        if (str.find('.') == str.size() - 1)
        {
            str.pop_back();
        }
        return str;
    }
    
    int main()
    {
        std::cout << RemoveTrailingZero(1.25) << std::endl;
        std::cout << RemoveTrailingZero(6.50) << std::endl;
        std::cout << RemoveTrailingZero(600.0) << std::endl;
    }
    

    Output:

    1.25
    6.5
    600