Thread: Trouble with a simple array

  1. #16
    Registered User
    Join Date
    Oct 2005
    Posts
    36
    thanks, ive figured it out....it seems when i switched computers, it would work...don't know why mine wasn't working.

  2. #17
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    Quote Originally Posted by ssharish2005
    there u go the working code.
    Code:
    #include <stdio.h>
    #include <math.h>
    #define SIZE 100
    
    int temp[SIZE];
    
    int main (void)
    {
    	int i, sum, sum_sqr,tempi;
    	double mean, st_dev;
    	FILE *inp;
    	
    	inp = fopen("C:\\Program Files\\Miracle C\\temperature.txt", "r");
    	
    	if (inp == NULL)
    	{
    		printf("ERROR OPENING THAT FILE\n");
    	}
    
    	/* Gather and prints all the data from the file */
    	for (i = 0; i<SIZE; i++) 
    	{
    		if(fscanf(inp, "%d", &temp[i])!=1)
    		break;
    		printf("%d\n", temp[i]);
    	}
    
    	/*Computes the sum and the sum of the squares of all the data*/
    	sum = 0;
    	sum_sqr = 0;
    	tempi=i;
    	for (i = 0; i < tempi; i++)
    	{
    		sum+=temp[i];
    		sum_sqr += temp[i] * temp[i];
    	}
    	/*Computes and prints the mean and standard deviation*/
    	mean = (double)sum / SIZE;
    	st_dev = sqrt(sum_sqr / SIZE - mean * mean);
    	printf("The mean is %.2f\n", mean);
    	printf("The standard deviation is %.2f.\n", st_dev);
    	
    	fclose(inp);
        getchar();
    	return (0);
    }
    /*myoutput
    1
    2
    3
    4
    5
    6
    7
    8
    9
    The mean is 0.45
    The standard deviation is 1.34.
    */
    ssharish2005
    You've got a logic error here, dividing by SIZE will only work when you actually read 100 items.....you're reading far less, which means youre computations are wrong, you need to divide by the number of items you actually read in, so you'll have to keep track of that somehow.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. base address of a simple array
    By nacho4d in forum C Programming
    Replies: 13
    Last Post: 04-07-2008, 01:28 PM
  2. Simple 2 dimensional array problem
    By AmbliKai in forum C Programming
    Replies: 4
    Last Post: 10-30-2007, 05:49 AM
  3. simple Array question.
    By Fredir in forum C++ Programming
    Replies: 6
    Last Post: 10-06-2007, 07:12 AM
  4. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  5. A simple question about selecting elements in an array
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 10:37 PM