为什么它不工作

why is setw not working?

本文关键字:工作 为什么      更新时间:2023-10-16
#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

。在"文件"中包含:6-56.765 2.3 4.56 -1.2 -1.8 3

程序首先显示"atestat"第二行上的所有数字。在"文件"中,通过使用一个数组,然后它应该显示该数组中所有负数的算术平均值,精度为小数点后2个数字。由于某种原因,setw(2)什么也没做,因为我的cout<<setw(2)<<s/nr<<endl;显示的是"19.9217"而不是"19.92"…有人能告诉我为什么吗?我是不是用错了?

,精度为小数点后2个数字

为此,您需要:

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

std::setw不能用于此目的:

当用于表达式out <<Setw (n) or in>> Setw (n),设置出流或入流的宽度参数正好为n。