Advertisement
MartinaLatifi

file_dati_random

Nov 20th, 2019
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. #define FILE_IN "numeri.txt" //file in cui ci saranno i numeri casuali generati da questo programma
  5. #define FILE_OUT "calcoli.txt"//fine in cui scriviamo media e deviazione standard
  6. #define N 1000 //numero di dati casuali
  7. #define STRLEN 256
  8. int main(void)
  9.     {
  10.         char s1[STRLEN],s2[STRLEN];
  11.         float min,max,x,somma2,somma;
  12.         int i;
  13.         FILE*pf;
  14.        
  15.         printf("Adesso ti chiederò due numeri: massimo > minimo. Se sbagli (cioè se mi dai massimo < minimo) te lo richiederò!\n");
  16.         do
  17.             {
  18.                 printf("Dammi il minimo (minore di 100):\n"); //il minore di 100 e' per evitare l'overflow
  19.                 scanf("%s",s1);
  20.                 min=atof(s1);
  21.                 printf("Dammi il massimo (minore di 100):\n");
  22.                 scanf("%s",s2);
  23.                 max=atof(s2);
  24.             }
  25.         while(min>=max);
  26.         //printf("min=%.3f e max=%.3f", min, max);
  27.         pf=fopen(FILE_IN,"w");
  28.         if(pf==NULL)
  29.             {
  30.                 printf("Non ho potuto aprire il file %s\n", FILE_IN);
  31.                 return EXIT_FAILURE;
  32.             }
  33.         srand(time(NULL));
  34.         for(i=0;i<N;i++)
  35.             {
  36.                 x=((((float)rand()/RAND_MAX))*(max-min))+min;
  37.                 fprintf(pf,"%.2f\n",x);
  38.             }
  39.         fclose(pf);
  40.         pf=fopen(FILE_IN,"r");
  41.         for(i=0,somma=somma2=0.0;i<=N;i++)
  42.             {
  43.                 fscanf(pf,"%s",s1);
  44.                 somma+=atof(s1);
  45.                 somma2+=(atof(s1)*atof(s1));
  46.             }
  47.         fclose(pf);
  48.         pf=fopen(FILE_OUT,"w");
  49.         if(pf==NULL)
  50.             {
  51.                 printf("Non ho potuto aprire il file %s\n", FILE_OUT);
  52.                 return EXIT_FAILURE;
  53.             }
  54.         fprintf(pf,"La media è: %.3f\nLa deviazione standard è: %.3f\n", (somma/N), ((somma2/N)-((somma/N)*(somma/N))));
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement