help:how to read array & the size of it from file!!

Hi there,i'm trying to read array & it's size from txt file(the size in the first row ,the numbers of the array in the second one) for calculating the average & deviasion of it put it's calculating wrong,anybody can help me?!..

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
  #include <iostream>
#include <cmath>
#include <fstream>
#include <string>
using namespace std;
double arr_average(double *a,int size);
double arr_standard_deviation(double *a,int size);
double*read_arr_from_file(string fname, int &size);
int main(int argc,char*argv[]){
	string fname="test1.txt"; int size;
	if (argc > 1) fname = argv[1];
	else{
		cout << "EROR:no arg found.\n";
		exit(1);
	}
	
	
	double*arr = read_arr_from_file(fname, size);
	cout << "Array Average:" << arr_average(arr,size) << "\n"
		<< "Array standard Deviation:" << arr_standard_deviation(arr, size)
		<< "\n";

	



	return (0);
}
double arr_average(double *a, int size){
	double sum = 0;
	for (int i = 0; i < size; i++){
		sum +=a[i];
		return (sum / size);
	}
}
double arr_standard_deviation(double *a, int size){
	double series = 0;
	for (int i = 0; i < size; i++){
		series += (a[i] - arr_average(a, size))*(a[i] - arr_average(a, size));
	}
	return sqrt((1 / size)*series);
}
double*read_arr_from_file(string fname,int &size){
	ifstream f(fname);
	if (!f){
		cout << "EROR:file do not exist\n";
		exit(1);
	}
	f >> size;
	double *ans = new double[size];
	for (int i = 0; i < size; i++){
		if (!(f >> ans[i])){
			cout << "EROR:reading file\n";
			exit(1);
		}
			}
	return ans;
	f.close();
}.
Last edited on
The problem with arr_average is that you have placed the return statement inside the loop.

The problem with the arr_standard_deviation is that you're dividing 1 and size which are two integers. Dividing two integers will do integer division giving you an integer quotient with the fractional part missing.
Topic archived. No new replies allowed.