output problem

My codes are okay so far.

My problem is when I type my 1st file name it displays the data in the file as integer and display the standard deviation as integer also.(This one is okay)

Then the 2nd data file input comes in and display the data as integer and display the standard deviation with decimal point.

My main problem starts after the 2nd data input when I type in my 3rd data input and the displayed data comes out with decimal point and also my standards deviation, when it should display only 4 but it display 4.0 .

Can someone tell me my problem or is it a limitation?





#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <math.h>
using namespace std;

const int MAX = 10;
const char MaxFileName = 11;

int main()
{
char response='y';
int counter;
int recordcount;
int sdint;
float number;
float next;
float medium;
float avg;
float sdfloat;
float difference;
float array [MAX];
float total;
char file[MaxFileName];


while (response == 'y' || response == 'Y')
{
cout << "Enter the filename of the data: ";
cin >> file;


ifstream fin;

fin.open (file);
if (fin.fail())
{
cout << "Opening file failed.\n";
system ("pause");
exit(1);
}
cout << endl;

counter = 0;
while (fin >> number && counter < MAX)
{
total = 0;
array [counter] = number;
counter ++;
}
cout << "The data are: "<<endl;

recordcount = counter;
for (counter = 0; counter < recordcount; counter ++)
{
cout << array [counter] <<" ";
total+= array [counter];
}
cout<<endl;
cout<<endl;

avg = total/recordcount;
total = 0;
for (counter = 0; counter < recordcount; counter ++)
{
medium = pow(array [counter] - avg, 2);
total+= medium;
}

sdfloat = sqrt(total/recordcount);
sdint = sdfloat;

difference = sdfloat - sdint;
if (difference < 0.5)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
cout << "The Standard Deviation is :" << sdfloat << " ";
}
else
{
cout << "The Standard Deviation is :" << ceil(sdfloat) << " ";

}

fin.close ();
cout<<endl<<"Enter 'y' to continue: ";
cin>>response;
cout <<endl;
}
system("pause");
return 0;
}
The solution is to cast the output as int.
cout << (int) array [counter] <<" ";
and
cout << "The Standard Deviation is :" << (int) sdfloat << " ";

The real problem with your code is that, once it has passed cout.precision(1);, every subsequent output of numbers has precision 1.
(Even if it is in a while loop and the program returns to the beginning of that loop, the precision stays set at 1 for every loop. Meaning integers and floating points.) Unless of course you set it back to cout.precision(0);. You can do this either at the start or at the very end of the while (response=='y'||response=='Y')-loop.
Last edited on
Topic archived. No new replies allowed.