Home > Software design >  Why won't the average column amount not calculate?
Why won't the average column amount not calculate?

Time:11-27

I want to print out the average amount of an 2D array column, by filling the matrix with random numbers

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    
    int m = 0;
    int n = 0;
    int array[m][n];
    double ran_num = (double)rand() / RAND_MAX;
    double avg_col[] = {0};
    
    printf("Enter (m, n > 0): ");
    scanf("%d, %d", &m, &n);
    
    for(size_t i = 0; i <= m;   i){
        for(size_t j = 0; j <= n;   j){
            array[i][j] = ran_num;
            avg_col[j]  = array[i][j] / m;
        }
    }
    
    for(int i = 0; i < n; i  ){
        printf("Average of column %d : %.3f\n", i ,avg_col[i]);
    }
    
    return 0;
}

But the output is:

Average of column 0 : 0.000
Average of column 1 : 0.000
Average of column 2 : 0.000

I can't figure out where the problem is. Maybe you can help me, I would really appreciate it.

CodePudding user response:

In this line:

avg_col[j]  = array[i][j] / m;

variable array[i][j] is an integer, and variable m is an integer.
So you are doing integer division. If the denominator m is greater than the numerator array[i][j], then the result is ZERO.

Example:

5 / 10; // Humans think the result is 0.5.  Programmers know the result is 0.

CodePudding user response:

Fixed up for you.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    
    int m = 0;
    int n = 0;
    
    printf("Enter (m, n > 0): ");
    scanf("%d, %d", &m, &n);
    
    double array[m][n];
    double avg_col[n];
    memset(avg_col, 0, sizeof(avg_col));
    
    for(size_t i = 0; i < m;   i){
        for(size_t j = 0; j < n;   j){
            array[i][j] = ((double)rand()) / RAND_MAX;
            avg_col[j]  = (double)array[i][j] / m;
        }
    }
    
    for(int i = 0; i < n; i  ){
        printf("Average of column %d : %.3f\n", i ,avg_col[i]);
    }
    
    return 0;
}

Output (with input 5, 10)

Success #stdin #stdout 0s 5460KB
Enter (m, n > 0): 5, 10
Average of column 0 : 0.475
Average of column 1 : 0.575
Average of column 2 : 0.460
Average of column 3 : 0.661
Average of column 4 : 0.588
Average of column 5 : 0.478
Average of column 6 : 0.480
Average of column 7 : 0.697
Average of column 8 : 0.356
Average of column 9 : 0.620
  • Related