Hello everyone,
I've recently started a programming course and for my first assignment, I was asked to produce a code that would be able to extract up to 100 (1-100) integers from a text file and then give the sum, mean and standard deviation.
My first instinct was to separate the task into two parts: first, I wrote the code for loading the integers into a 1D array. Second, I used a hardcoded array to develop the necessary equations for sum, mean and standard deviation. However, when I combine the two parts, two problems arise:
1)
When I substitute the hardcoded array for the one filled with data from file, the program gives the wrong answers. Upon inspection, I noticed that the array used for sum/mean/sd calculations is nothing like the one loaded from file (which loads successfully), its full of 0s but also some incredibly large numbers.
2)
For some reason, when I have two identical projects open, the break command on eof (line 29) only works in one - when I print the array for the other project, I still get two 100s as my penultimate and final integers.
Any hints or comments would be greatly appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <stdio.h>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
using namespace std; //tells computer to use a particular library of C++ commands
int main()
{
float sum, mean = 0.0;
float var, dev, sd, sdev = 0.0;
int i,n = 0;
int Array [100];
ifstream integers;
integers.open("StatNum.txt");
if(!integers) cout << "Error opening file.\n";
while (!integers.eof())
{
integers >> Array[i];
cout << Array[i] <<endl;
if(integers.eof() ) break; //prevents from reading the last line again
}
integers.close();
for (n=0; n<100; n++) //loop the array to get sum and mean
{
sum += Array[n];
mean = sum/(n+1);
}
for(n = 0; n < 100; n++) //std dev loop
{
dev = (Array[n] - mean)*(Array[n] - mean);
sdev = sdev + dev;
}
var = sdev / (n - 1);
sd = sqrt(var);
cout <<endl << setprecision(2)<<fixed<< "The sum of " << n << " integers is: " << sum << endl; //output
cout << "The average of " << n << " integers is: " << mean <<endl;
cout << "The standard deviation of " << n << " integers is: " <<sd << endl;
system("pause"); //on windows it might exit immediately
return(0);
}
|