下面的代码将a,b,c,d的值显示为小数点后四位,e的值显示为小数点后一位。但是,当我运行该函数时,所有五个变量都位于小数点后一位。您能告诉我我的代码有什么问题以及如何解决它吗?
#include <iomanip>
#include <algorithm>
#include <vector>
struct Record{
int year;
string name;
string team;
double completions, attempts, yards, touchdowns, interceptions, e;
};
void passerRate ()
{
double a, b, c, d, e;
//quarterbacks is a vector of struct
for (int i = 0; i < quarterbacks.size(); i++){
Record player = quarterbacks[i];
a = (player.completions / player.attempts - 0.3) * 5;
b = (player.yards / player.attempts - 3) * 0.25;
c = (player.touchdowns / player.attempts) * 20;
d = 2.375 - (player.interceptions / player.attempts * 25);
cout << fixed << setprecision(4); // I want to set the precision of a,b,c,d to four decimal places
e = (a + b + c + d) / 6 * 100;
cout << fixed << setprecision(1); //I want to set the precision of e to one decimal place
quarterbacks[i].e = e;
}
最佳答案
cout << setprecision(4) << fixed;
行仅会影响此后如何将十进制值显示到标准输出。这是两个应该可以帮助您的解决方案。如果您想要的是将数字本身四舍五入后再用于其他计算,那么以下内容将很适合您:
double x = 1.23456;
double x1 = round(x); // x1 is x rounded to nearest whole number
double x2 = round(x * 10.0) / 10.0; // x2 is x rounded to nearest tenth
double x3 = round(x * 1000.0) / 1000.0; // x3 is x rounded nearest thousandth
否则,您可以在打印语句之间设置标准输出的精度,如下所示:
cout << setprecision(4) << fixed; // cout will now print 4 decimal places
cout << "a = " << a << endl;
cout << setprecision(1); // cout will now print 1 decimal place
cout << "e = " << e << endl;