有没有一种方法可以更具体地用C ++格式化输出?

时间:2020-04-05 06:55:28

标签: c++ output iomanip

当我将setprecision()中的值分配给1

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

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

因此,当我将setprecision()中的值更改为2

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

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

我该怎么做才能在两种情况下都能正确输出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;

}

1 个答案:

答案 0 :(得分:2)

您可以编写一些帮助程序功能,以所需的方式格式化字符串。我已经在代码中添加了注释以进行解释。

#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