-2

I have created a program in C to calculate the average, variance, maximum, and minimum of a list of numbers that user inputs, and the number of user inputs is decided by the first user input.

#include <stdio.h>
#include <float.h>

int main(int argc, char** argv)
{
    int size;
    
    scanf("%d", &size);
    
    double num[size-1];
    double sum = 0;
    double dx = 0;
    double max = num[0];
    double min = num[0];
    double avg, var;

    for(int i = 0; i < size; i++){
        scanf("%lf", &num[i]);
    }
    
    for(int i = 0; i < size; i++){
        sum += num[i];
        if(num[i] < min){
            min = num[i];
        }
        if(num[i] > max){
            max = num[i];
        }
    }
    
    avg = sum/(double)size;
    for(int i = 0; i < size; i++){
        dx += ((num[i]-avg)*(num[i]-avg));

    }

    var = dx/(double)(size);

    printf("AVG: %0.4f\n", avg);
    printf("VAR: %0.4f\n", var);
    printf("MAX: %0.4f\n", max);
    printf("MIN: %0.4f\n", min);
    return 0;
}

However, when I run the program it always outputs 0 for the minimum, and I am not sure why this program does that. Any advice on the code/help is greaty appreciated.

Steven Oh
  • 382
  • 3
  • 14
  • 4
    Your initialization of `min` and `max` don't make sense: `double min = num[0];` The array is not initialized. You are using indetermined values. Move that part after you read in the values for your array. Also the size of your array does not make sense: `double num[size-1];` You read in `size` elements. That will access the array out of bounds because it is too small. – Gerhardh Nov 19 '22 at 07:52
  • [this thread](https://stackoverflow.com/questions/64731546/how-to-find-a-minimum?rq=1) looks similar – emetsipe Nov 19 '22 at 10:38
  • just add correct version for `double num[size-1];` as @Gerhardh does not provide correction. It should be `double num[size];` – ThongDT Nov 19 '22 at 10:51

1 Answers1

-2

Problem is initial values of your min and max variables are assigned prior to user input.

#include <stdio.h>
#include <float.h>

int main(int argc, char** argv)
{
    int size;
    
    scanf("%d", &size);
    
    double num[size-1];
    double sum = 0;
    double dx = 0;
    double max;
    double min;

    for(int i = 0; i < size; i++){
        scanf("%lf", &num[i]);
    }

    max=num[0];
    min=num[0];
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
ssps
  • 16
  • 2