使用流时,如何返回8.0而不是8?

时间:2018-10-15 08:46:14

标签: c++ ostream

此代码的格式和输出与我的作业的示例输出匹配,但是问题是,当我希望将其作为8时,我将返回8.0

我该怎么办?

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

void runningSum(istream &in, ostream &out)
{
    string line, str;
    double sum = 0, max = 0;
    while (getline(in, line))
    {
        istringstream sin(line);
        out << "running sum = ";
        while (sin >> str)
        {
            sum = sum + stod(str);
            out << sum << " ";

            if(max < sum) max = sum;
        }
        out << "\nmax sum = " << max << endl;
    }
}

int main()
{
    ifstream in("in.txt");
    runningSum(in, cout);
    return 0;
}
// in.txt: 3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25
// my output:
// running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8 13.25
// max sum = 14.5
// desired output:
// running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8.0 13.25
// max sum = 14.5

1 个答案:

答案 0 :(得分:1)

您的代码相当明智,要求有些棘手。

我建议编写一个函数以所需的格式格式化double,并在必要时添加结尾的“ .0”

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>

std::string format(double value)
{
    std::stringstream ss;
    ss << value;
    // check for existing decimal point
    if (ss.str().find('.') == std::string::npos)
    {
        ss << ".0";
    }
    return ss.str();
}

void runningSum(istream &in, ostream &out)
{
    for (std::string line; getline(in, line);)
    {
        double sum = 0;
        double max = std::numeric_limits<double>::lowest(); // could be always negative
        std::istringstream sin(line);
        out << "running sum = ";
        for (double value; sin >> value;)
        {
            sum += value;
            out << format(sum) << " ";

            max = std::max(max, sum);
        }
        out << "\nmax sum = " << format(max) << "\n";
    }
}

int main()
{
    std::ifstream in("in.txt");
    runningSum(in, std::cout);
    return 0;
}