9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex30_std_dev.c (1004B)
   1 //    Calculates the arithmetic mean of a certain amount of
   2 //    numbers. First ask for the quantity and then calculates
   3 //    it and prints it;
   4 
   5 #include <stdio.h>
   6 #include <stdlib.h>
   7 #include <math.h>
   8 
   9 #define MAX_LEN 20
  10 
  11 int main (void) {
  12 
  13     int i, n;
  14     float d, x, suma, numbers[MAX_LEN];
  15     char buffer[MAX_LEN];
  16 
  17 //    Read the quantity of numbers to mean;
  18     if(fgets(buffer, sizeof(int) + 1, stdin) != NULL)
  19         n = atoi(buffer);
  20     else return 1;
  21 
  22 //    Read the values to mean  and stores it on numbers;
  23     for(i = 0, suma = 0; i < n; i++) {
  24         if(fgets(buffer, sizeof(int) + 1, stdin) != NULL) {
  25             numbers[i] = atof(buffer);
  26             suma += numbers[i];
  27         } else return 1;
  28     }
  29 
  30 //    Calculate the arithmetic mean and stores it on x;
  31     x = ((1 / (float)n) * suma); 
  32 
  33 //    Calculates the standard deviation;
  34     for(i = 0; i < n; i++) {
  35         suma += (numbers[i] - x);
  36         d = sqrtf((1/n) * powf(suma, 2.0));
  37     }
  38 
  39 //    Print the arithmetic mean;
  40     printf("x = %.3f\n", x);
  41 
  42 //    Print the standard deviation;
  43     printf("d = %.3f\n", d);
  44     return 0;
  45 }