Home > OS >  Calculating minimum of a list of numbers — output error
Calculating minimum of a list of numbers — output error

Time:11-21

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.

CodePudding user response:

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];
  • Related