0
#include<fstream.h>
#include<iomanip.h>
#include<iostream.h>
using namespace std;
ifstream f("atestat.in");
ofstream g("atestat.out");
int n,i,nr=0;
float v[100];
void a(int n)
{
    for(i=1;i<=n;i++)
        f>>v[i];
    for(i=1;i<=n;i++)
    cout<<v[i]<<" ";
}
int main()
{
    f>>n;
    a(n);
    cout<<endl;
    float s=0;
    for(i=1;i<=n;i++)
    {
        if(v[i]<0)
        {   
        s=s+v[i];
        nr++;
        }
    }
    cout<<setw(2)<<s/nr<<endl;
}

我的“atestat.in”文件包含:6 -56.765 2.3 4.56 -1.2 -1.8 3

该程序首先显示“atestat.in”文件第二行的所有数字,通过使用一个数组,然后它应该显示该数组内所有负数的算术平均值,精度为小数点后2个数字。出于某种原因, setw(2) 什么都不做,因为我cout<<setw(2)<<s/nr<<endl;显示的是“19.9217”而不是“19.92”......谁能告诉我为什么?我是否以某种方式不当使用它?

4

1 回答 1

2

精度为小数点后 2 个数字

为此,您需要:

std::cout << std::fixed;
std::cout << std::setprecision(2) << f << '\n'; //assume f the number you wanna print

std::setw不用于此目的:

当在表达式 out << setw(n) 或 in >> setw(n) 中使用时,将流输出或输入的宽度参数设置为正好 n。

于 2013-05-18T22:17:44.207 回答