简体   繁体   English

为什么setw不工作?

[英]why is setw not working?

#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;
}

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

The program first displays all the numbers on the second line of the "atestat.in" file, through the use of an array, and then it is supposed to display the arithmetic mean of all the negative numbers inside that array, with a precision of 2 numbers after the decimal mark. 程序首先显示“atestat.in”文件第二行的所有数字,通过使用数组,然后它应该显示该数组内所有负数的算术平均值,精度为小数点后的2个数字。 For some reason, setw(2) does nothing at all, as my cout<<setw(2)<<s/nr<<endl; 出于某种原因,setw(2)什么都不做,因为我的cout<<setw(2)<<s/nr<<endl; displays "19.9217" instead of "19.92"...could anyone tell me why? 显示“19.9217”而不是“19.92”......有谁能告诉我为什么? Am i using it improperly somehow? 我是不是以某种方式不正确地使用它?

with a precision of 2 numbers after the decimal mark 小数点后的精度为2

For this purpose, you need: 为此,您需要:

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

std::setw does not serve for this purpose: std :: setw不用于此目的:

When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n. 当在表达式<< setw(n)或in >> setw(n)中使用时,将流的宽度参数设置为out或in到n。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM