使用流时如何 return 8.0 而不是 8?

How do I return 8.0 instead of 8 when using streams?

此代码的格式和输出与我的作业示例输出匹配,但问题是当我希望它是 8.0.

时我返回 8

我该怎么办?

#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

你的代码还算合理,只是要求有点棘手。

我的建议是编写一个函数来将 doubles 格式化为所需的形式,必要时添加尾随“.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;
}