是否有一种方法可以在C ++中更具体地格式化输出?

问题描述 投票:1回答:1

[当我将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;

}
c++ output iomanip
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.