1
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>

using std::cin; using std::sort;
using std::cout; using std::streamsize;
using std::endl; using std::string;
using std::setprecision; using std::vector;
int main()
{

    cout << "Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    cout << "Enter all your homework grades, "
        "followed by end-of-file: ";
    vector<double> homework;
    double x;

    while (cin >> x)
        homework.push_back(x);

        int size = homework.size();
        if (size == 0) {
                    cout << endl << "You must enter your grades. "
                    "Please try again." << endl;
                    return 1;
                        }

    sort(homework.begin(), homework.end());

    int mid = size/2;
    double median;
    median = size % 2 == 0 ? (homework[mid] + homework[mid-1]) / 2
            : homework[mid];

    streamsize prec = cout.precision();
    cout << "Your final grade is " << setprecision(3)
        << 0.2 * midterm + 0.4 * final + 0.4 * median
        << setprecision(prec) << endl;
return 0;
}

在这个例子中,“streamsize”的意义何在?为什么 cout.precision() 会这样设置?以下行有“setprecision(3)”,然后在末尾再次有 setprecision(prec)。这是为什么?

streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
    << 0.2 * midterm + 0.4 * final + 0.4 * median
    << setprecision(prec) << endl;
4

2 回答 2

2

该代码将精度重置为std::cout原始值,以便后续使用std::cout不使用三位精度。

我建议使用范围保护,这样即使在setprecision(3)and之间抛出异常,精度也会被重置setprecision(prec)

于 2013-10-05T13:54:17.697 回答
1

原因是作者想设置他打印的值的精度,但为以后使用它的每个人保留流的现有精度。

使用的原因streamsize很简单:它是从cout.precision().

于 2013-10-05T13:54:22.173 回答