/* Programmazione II - Esempio di codice Example code: linked list demonstration. (20000808 prelz@mi.infn.it) */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* Let's use a simpler structure */ typedef struct measurement_s { double value; char comments[120]; struct measurement_s *next; } measurement; #define SAFE_ASSIGN(string,value) \ (string)[sizeof(string)-1] = '\000'; \ strncpy((string),value,sizeof(string)-1); int main(int argc, char *argv[]) { char in[800]; /* Generic input storage */ int record_count = 0; measurement *record_head = NULL; measurement *record_tail = NULL; measurement *new_record; measurement *cur_record, *next_record; double old_average, average=0, nvariance=0, variance; int i; for (;;) { /* Infinite data entry loop. Will exit with break. */ printf ("********* Now processing record # %d.\n",record_count+1); printf ("Would you like to add a new record ? (Y/N): "); fgets(in, sizeof(in), stdin); if (in[0] != 'y' && in[0] != 'Y') break; new_record = (measurement *)malloc(sizeof(measurement)); if (new_record == NULL) { fprintf(stderr,"Warning: Out of Memory.\n"); continue; } printf ("Measurement value --->"); fgets(in, sizeof(in), stdin); new_record->value = atof(in); printf ("Any comments ? --->"); fgets(in, sizeof(in), stdin); in[strlen(in)-1] = '\000'; /* Remove trailing newline */ SAFE_ASSIGN(new_record->comments,in); printf ("\n\nI have the following data:\n"); printf ("Meas. value: %g\n", new_record->value); printf ("Comments: %s\n", new_record->comments); printf ("\nIs it OK to store these data ? (Y/N): "); fgets(in, sizeof(in), stdin); if (in[0] != 'y' && in[0] != 'Y') { free(new_record); /* This is very important!! */ continue; } printf("\n"); record_count++; /* Append to the linked list tail */ if (record_tail != NULL) { record_tail->next = new_record; } record_tail = new_record; /* Set head pointer if necessary */ if (record_head == NULL) record_head = new_record; } /* Let's now loop over the collected data */ for (i=0,cur_record = record_head; cur_record!=NULL; i++,cur_record = cur_record->next) { printf ("\n********* Record # %d.\n\n",i+1); printf ("Meas. value: %15.13g\n", cur_record->value); printf ("Comments: %s\n", cur_record->comments); /* Compute average and std. deviation values */ old_average = average; average = (double)i/(double)(i+1)*average + (double)1/(double)(i+1)*cur_record->value; nvariance = (double)1/(double)(i+1) * ( (double)(i) * nvariance + pow(cur_record->value,2) + (double)i * pow(old_average,2) - (double)(i+1) * pow(average,2) ); if (i > 0) variance = (double)(i+1)*nvariance/(double)i; else variance = nvariance; printf ("Current average: %15.13g\n",average); printf ("Current std dev: %15.13g\n",sqrt(variance)); } printf("\n"); /* Destroy and free the list */ for (cur_record = record_head; cur_record!=NULL; cur_record = next_record) { next_record = cur_record->next; free(cur_record); } exit(0); }