Search code examples
csumaverage

Find Sum and Average function not returning actual value of Average


Here's my function that returns the Sum of all pair numbers in an array, and the Average of Odd numbers. Although it outputs the Average as zero for some reason.

 #include <stdio.h>
 
 int MoySom(int Tab[],float* Moyenne,int Length)
 {
     int S=0,C=0;
     *Moyenne=0;
     for(int i=0;i<Length;++i)
     {
         if(Tab[i] % 2 == 0)
         {
             S=S+Tab[i];
         }
         else if(Tab[i] % 2 != 0)
         {
             *Moyenne+=Tab[i];
             ++C;
         }
     }
     *Moyenne=*Moyenne/C;
     return S;
     
 }
 
 void main()
 {
     int Length,Tab[Length];
     float Moyenne;
     printf("Entrer la longeur de tableau: ");
     scanf("%d",&Length);
     for(int i=0;i<Length;++i)
     {
         printf("Entrer l'element %d: ",i);
         scanf("%d",&Tab[i]);
     }
     printf("Somme est:%d\nMoyenne est: %.2f",
         MoySom(Tab,&Moyenne,Length), Moyenne);
 }

Solution

  • At least these problems:

    Wrong declaration order

    int Length,Tab[Length]; is junk. The declaration of Tab[Length] is happening, yet the value of Length is indeterminate.

    Something more like the below. Declare Tab[] after Length is assigned.

     int Length;
     float Moyenne;
     printf("Entrer la longeur de tableau: ");
     scanf("%d",&Length);
     int Tab[Length];
    

    Better code checks the return value of scanf()

     int cnt = scanf("%d",&Length);
     if (cnt != 1 || Length <= 0) {
       Report_Error_and_exit();
     } 
     int Tab[Length];
    

    Parameter evaluation order assumed

    Calculate Moyenne, then used use it.

    //printf("Somme est:%d\nMoyenne est: %.2f",
    //     MoySom(Tab,&Moyenne,Length), Moyenne);
    
    printf("Somme est:%d\n", MoySom(Tab,&Moyenne,Length));
    printf("Moyenne est: %.2f", Moyenne);
    

    Potential /0

    *Moyenne=*Moyenne/C; may attempt divide by zero. Better code would prevent that.

    Unneeded test

         if(Tab[i] % 2 == 0) {
           S=S+Tab[i];
         } else if(Tab[i] % 2 != 0) {
           *Moyenne+=Tab[i];
    

    simplifies to

         if(Tab[i] % 2 == 0) {
           S=S+Tab[i];
         } else {
           *Moyenne+=Tab[i];