Home > Software design >  Weird bug in C: Different results to the same function sometimes right sometimes wrong
Weird bug in C: Different results to the same function sometimes right sometimes wrong

Time:06-13

So I am trying to run this code where I calculate the mean and median in 2 functions. When I use these functions in my main function and run my program, sometimes it gives me the right answer and sometimes it gives me some random numbers for the mean even though I run the exact same code. Can somebody explain this behavior to me? Any help is appreciated.

    float mean(int *numbers, int n){
        int i=0;
        float solution;
        float tmp_m;
    
        for(i=0; i<n; i  ){
            tmp_m=(float)numbers[i] tmp_m;
        }
            
        solution=tmp_m/((float)n);
    
        return solution;
    }
    
    float median(int *numbers, int n){
        float median;
        float median_b;
        int index;
        int index_b;
    
        if(n % 2 == 1){
            index=n/2;
            median= (float)numbers[index];
            return median;
    
        }else if (n % 2 == 0){
            index_b=n/2;
            float tmp_median;
            tmp_median= (float)numbers[index_b]   (float)numbers[index_b-1];
            median_b=tmp_median/((float)2);
            return median_b;
    
        }
    }
    
    #include <stdio.h>
    
    int main () {
        int array[6]={0,2,3,4,0,5};
        int n=6;
        
        float result=mean(array, n);
        float result_median=median(array, n);
    
        printf("%f\n%f\n", result, result_median);
    
        return 0;
    }

CodePudding user response:

The variable tmp_m is left uninitialized and it gives you random values. So, replace float tmp_m; with float tmp_m = 0; in the mean function.

CodePudding user response:

You haven’t initialised tmp_m to zero before using it.

  •  Tags:  
  • c
  • Related