Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.8 kB
7
Indexable
Never
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "806_Grade_Calculator.h"
double CharToDouble(char *s){
  int len = 0;
  while( *(s+len) != '\0' ){ len++; }
  len--;
 
  int ans = 0;
 
  // printf("---\ns = %s, len = %d\n---\n", s, len);
  for(int i=0; i<len; i++){
    //printf(" *(s+i) = %c\n", *(s+i) );
    //printf(" -> %d\n", (*(s+i) - '0') );
    ans += ( *(s+i) - '0' ) * pow(10, len - 1 - i);
  }
 
  //printf(" ans = %d\n", ans);
  return (double) ans;
}
 
 
void CalcVariance(char *csv_text, double *mean_array, double *variance_array, int row, int column){
  /*
  1. Using strtok to split the string
  2. Using CharToDouble to convert string to double
  3. Calculating mean and varianc
  */
 
  csv_text++;
  // printf("-%s-", csv_text);
 
  char *s;
  s = strtok(csv_text, "\n,");
  int len;  
  int num_list[row][column];
 
  for(int i=0; i<row*column; i++){
    len = strlen(s);
    // printf("s = %s; len = %d\n", s, len);
    int num = 0;
    for(int j=0; j<len; j++){
      num += ( s[j] - '0' ) * pow(10, len-1-j);
    }
    // printf("-> num = %d\n", num);
 
    num_list[i / column][ i % column ] = num;
 
    s = strtok(NULL, "\n,");
  }
  /*
  for(int i=0; i<row; i++){
    for(int j=0; j<column; j++){
      printf("%d ", num_list[i][j]);
    }
    printf("\n");
  }
  */
 
  // mean
  for(int i=0; i<column; i++){
    int sum = 0;
    for(int j=0; j<row; j++){
      sum += num_list[j][i];
    }
    *(mean_array + i) = (double) sum / row;
  }
 
  // variance
  for(int i=0; i<column; i++){
    int sum = 0;
    for(int j=0; j<row; j++){
      sum += (num_list[j][i] - *(mean_array + i) ) * (num_list[j][i] - *(mean_array + i) );
    }
 
    *(variance_array + i) = sqrt( (double) sum / row );
  }
}
Leave a Comment