有没有办法在 C++ 中更具体地格式化输出?

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

当我将setprecision()中的值赋值给1

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

作为值输入,MyProgrammingLab 说我在 average 的输出中有错误。我的程序在应该显示 1.25 时显示 1.2

所以当我将 setprecision() 中的值更改为 2

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

作为值输入,MyProgrammingLab 再次说我在 average 的输出中有错误。当我的程序应该只显示 6.5 时却显示 6.50

我该怎么做才能在两种情况下正确输出 average

#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;

}

您可以编写一个小辅助函数来按照您想要的方式格式化字符串。我在我的代码中添加了注释来解释。

#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;
}

输出:

1.25
6.5
600