需要帮助我C.

时间:2015-10-24 20:13:00

标签: c

任何人都可以解释一下这是如何运作的?

void matr(int arr[max][max], int n, int m){

int i, k;
for (i = 0, k = m * n; i < k; i++)
{
    arr[i / m][i % m] = rand() % 10 * (pow(-1, rand() % 10));
}}

1 个答案:

答案 0 :(得分:1)

给出这段代码:

void matr(int arr[max][max], int n, int m)
{

    int i;
    int k;

    for (i = 0, k = m * n; i < k; i++)
    {
        arr[i / m][i % m] = rand() % 10 * (pow(-1, rand() % 10));
    }
}

这是一个解释:

1) MAX must be a #define or enum value  
   cannot be sure of which as that detail was not posted

2) `int arr[max][max]` is a pointer to a 2D array
   with max rows and max columns

3) `int n, int m` we can assume are the number or rows and columns to be filled in
   unfortunately with such extremely poor/meaningless parameter names
   it is difficult to be sure of their meaning.
   Also, both 'n' and 'm' must be <= 'max'

4) `int k;` should really have been: `int k = m*n;`
   and that calculation not placed in the 'for() statement, first parameter.
   why the whole 2D matrix is not being filled is a good/unanswered question.

5) `for (i = 0, k = m * n; i < k; i++)`  means loop m*n times with loop counter 'i'

6) `arr[i / m][i % m]`  this is a calculation of which row/column
   to place the produced value into.
   notice that this fills the matrix a row at a time
   however, if 'm' is not equal to 'n' then this calculation is flawed

7) `rand() % 10` get a number in the range 0...9 inclusive

8) `rand() % 10)` get a number in the range 0...9 inclusive

9) `(pow(-1, rand() % 10)` get the -1 to the 0...9 (inclusive) power
   which will produce both positive and negative values 
   depending on if the 'power' value is even or odd