joshiapoorav
joshiapoorav

Reputation: 63

How can I calculate the minimum value of numbers that are found in a .txt file using the C programming language?

I am trying to scan a .txt file and calculate the minimum GPA, maximum GPA, and average GPA using some pointers in the C programming language. A sample of the .txt file is below, it contains a student number and a gpa, separated by a comma.

123, 5.6
321, 4.2
458, 1.2
64, 3.678
82, 1.2091

I have attached my code down below. I have figured out how to find the maximum and average GPAs, but I am having quite a bit of difficulty finding the minimum GPA.

void calcStats(FILE* inFile, double* avgGPAptr, double* maxGPAptr, double* minGPAptr){
    double sum = 0, GPA, line = 0;

    while(fscanf(inFile, "%*d %*c %lf", &GPA) == 1){
        sum = sum + GPA;
        line = line + 1;
 
        if(GPA < *minGPAptr){    /*This is the part of the code where I am running into a problem*/
            *minGPAptr = GPA;
        }
        if(GPA > *maxGPAptr){
            *maxGPAptr = GPA;
        }
    }

    *avgGPAptr = sum/line;

    printf("Average GPA: %.2lf \n", *avgGPAptr);
    printf("Minimum GPA: %.2lf \n", *minGPAptr);
    printf("Maximum GPA: %.2lf \n", *maxGPAptr);
}

The maximum and average GPA calculations work as expected, but the minimum always ends up equaling 0.

If you could help me out with this, that would be great.

Upvotes: 0

Views: 81

Answers (2)

chux
chux

Reputation: 153338

With calcStats() notice that code nicely ignores any previous *avgGPAptr and simply sets *avgGPAptr.

void calcStats(FILE* inFile, double* avgGPAptr, double* maxGPAptr, double* minGPAptr){
  ... 
  *avgGPAptr = sum/line;
}

Yet GPA < *minGPAptr relies on the value of *minGPAptr prior to the calcStats() call. This is certainly causing OP's trouble.

void calcStats(FILE* inFile, double* avgGPAptr, double* maxGPAptr, double* minGPAptr){
    ... 
    if(GPA < *minGPAptr){ 

Instead, simply set GPA < *minGPAptr at the start of calcStats() to extreme values.

#include <float.h>

void calcStats(FILE* inFile, double* avgGPAptr, double* maxGPAptr, double* minGPAptr){
  *maxGPAptr = -DBL_MAX;
  *minGPAptr = DBL_MAX;
  ...
    ... 
    if(GPA < *minGPAptr){ 

Upvotes: 0

dbush
dbush

Reputation: 223699

You don't show how this function is called, but presumably *minGPAptr has a value of 0 when the function is called. So any positive value that is subsequently read in will be larger than that.

One way you can handle this is by ensuring *minGPAptr is set to a value larger than any valid value before you start reading anything. Then the first value will be smaller than that and become the minimum. You should do the same for *maxGPAptr, setting it smaller than any valid value to start.

 *minGPAptr = 999999;
 *maxGPAptr = -1;
 while(fscanf(inFile, "%*d %*c %lf", &GPA) == 1){

Upvotes: 3

Related Questions