mercredi 29 septembre 2021

How to count how many the non-zero value in a row in 2d array in C

How can I calculate how many non-zero values include in a row

I try to calculate the average of the total value inside a row but somehow it is always dividend in 5 How can I create a counter to count how many non-zero value inside the array?

Sorry for my bad english

int main () 
{
    float Sum, average;

    float a[4][5] = { {2.30,4.00,5.00},
                      {3.00,2.10,1.00,4.00},
                      {1.00,2.00,3.00,4.00,5.00},
                      {4.00,2.50}};
    int rows, columns;
    int length;
 
 
    for(rows = 0; rows < 4; rows++)
    {
        Sum = 0;
        for(columns = 0; columns < 5; columns++)
        {
        
            Sum = Sum + a[rows][columns];
        }
        
        printf("The Sum of rows Elements in a Matrix =  %.2f \n", Sum );
        average = Sum / columns;
        printf("Product %d : %f\n",rows + 1,average);
    }
    

      
      return 0;
   }

The output cames out is:

The Sum of rows Elements in a Matrix =  11.30
Product 1 : 2.260000
The Sum of rows Elements in a Matrix =  10.10
Product 2 : 2.020000
The Sum of rows Elements in a Matrix =  15.00
Product 3 : 3.000000
The Sum of rows Elements in a Matrix =  6.50
Product 4 : 1.300000

But I was aspect it will comes out

The Sum of rows Elements in a Matrix =  11.30
Product 1 : 3.77
The Sum of rows Elements in a Matrix =  10.10
Product 2 : 2.53
The Sum of rows Elements in a Matrix =  15.00
Product 3 : 3.00
The Sum of rows Elements in a Matrix =  6.50
Product 4 : 3.25

Aucun commentaire:

Enregistrer un commentaire