简体   繁体   English

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

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

When I assign the value in setprecision() to 1当我将setprecision()中的值分配给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 .被输入为值,MyProgrammingLab 说我在 output 中有一个错误 for average My program displays 1.2 when it should display 1.25 .我的程序应该显示1.2时显示1.25

So when I change the value in setprecision() to 2因此,当我将setprecision()中的值更改为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 .作为值输入,MyProgrammingLab 再次说我在 output 中有一个错误 for average My program displays 6.50 when it should only display 6.5 .我的程序应该只显示6.50时显示6.5

What can I do so that average is outputted correctly in both instances?我该怎么做才能在两种情况下正确输出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;

}

You could write a little helper function that formats the string the way you want.您可以编写一个小助手 function 以您想要的方式格式化字符串。 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: Output:

1.25
6.5
600

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM