gpt4 book ai didi

c++ - streamsize prec = cout.precision(); 的重点是什么?和以下几行?

转载 作者:行者123 更新时间:2023-11-30 02:52:11 25 4
gpt4 key购买 nike

#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)”,然后在末尾再次设置precision(prec)。这是为什么?

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

最佳答案

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

我建议使用 scope guard , 因此即使在 setprecision(3)setprecision(prec) 之间抛出异常,精度也会被重置。

关于c++ - streamsize prec = cout.precision(); 的重点是什么?和以下几行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com