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

my "atestat.in" file contains: 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. For some reason, setw(2) does nothing at all, as my cout<<setw(2)<<s/nr<<endl; displays "19.9217" instead of "19.92"...could anyone tell me why? Am i using it improperly somehow?

Juggl3r
  • 3
  • 1
  • 5
  • 4
    Did you look at any documentation for `std::setw`? Also, I can tell your compiler is really old because it accepts those removed headers. Remove the `.h` from them, and upgrade the compiler if you can. – chris May 18 '13 at 22:17
  • yes, I've been searching for a reason for which it may not work, and I've seen examples of it's use and etc., but the code I used seems fine to me...so I really have no idea – Juggl3r May 18 '13 at 22:19
  • it is the compiler I must use for a project...I know it's pretty old but it's what they make us use so that's that. Also, it doesn't make any difference if I put .h or not, I'm just used to putting it. – Juggl3r May 18 '13 at 22:20

1 Answers1

2

with a precision of 2 numbers after the decimal mark

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:

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.

taocp
  • 23,276
  • 10
  • 49
  • 62
  • yes, I know I can use setprecision, but that means that everything I will display later will also be displayed with a precision of 2 numbers, unless I change the precision everytime...is there no way around this? – Juggl3r May 18 '13 at 22:22
  • @GîdeiCodrin see an example from the documentation? http://en.cppreference.com/w/cpp/io/manip/setprecision – taocp May 18 '13 at 22:24
  • unfortunately I fail to see how that example answers my question...could you please explain if it does ? – Juggl3r May 18 '13 at 22:33