如何移动最大数量的矩阵

时间:2014-12-14 17:04:25

标签: c matrix

我需要将最大数量的随机生成的矩阵移动到矩阵的右下角,但我不知道如何。有人可以帮忙吗 这是我的代码:

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

int main()
{
    int i, j, rows, columns;
    int **matrix;

    printf("write the number of rows\n");
    scanf("%d", &rows);
    printf("write the number of columns\n");
    scanf("%d", &columns);

    matrix = malloc(rows * sizeof *matrix);
    for (i = 0 ; i < rows ; i++)
    {
        matrix[i] = malloc(columns * sizeof(int));
        for (j = 0 ; j < columns ; j++)
            matrix[i][j] = rand() % 100;
    }

    for (i = 0 ; i < rows ; i++)
    {
        for (j = 0 ; j < columns ; j++)
            printf("%5d", matrix[i][j]);
        printf("\n");
    }

    for (i = 0 ; i < rows ; i++)
    free(matrix[i]);
    free(matrix);

    return 0;
}

2 个答案:

答案 0 :(得分:-1)

尝试以下

int max = matrix[0][0];

for (i = 0 ; i < rows ; i++)
{
    for (j = 0 ; j < columns ; j++)
    {
        if ( max < matrix[i][j] ) max = matrix[i][j];
    }
}

matrix[rows-1][columns-1] = max;

如果你需要用最大元素交换矩阵的右下元素,那么代码看起来像

int max_i = 0;
int max_j = 0;

for (i = 0 ; i < rows ; i++)
{
    for (j = 0 ; j < columns ; j++)
    {
        if ( matrix[max_i][max_j] < matrix[i][j] ) max_i = i, max_j = j;
    }
}

int tmp = matrix[rows-1][columns-1];
matrix[rows-1][columns-1] = matrix[max_i][max_j];
matrix[max_i][max_j] = tmp;

答案 1 :(得分:-2)

您可以通过这种方式生成具有所请求功能的矩阵

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

int main()
{
    int i, j, rows, columns, largest, largestRow, largestColumn, swapValue;
    int **matrix;

    printf("write the number of rows\n");
    scanf("%d", &rows);
    printf("write the number of columns\n");
    scanf("%d", &columns);

    largest       = 0;
    largestRow    = 0;
    largestColumn = 0;
    matrix        = malloc(rows * sizeof *matrix);
    if (matrix == NULL)
        return -1;
    for (i = 0 ; i < rows ; i++)
    {
        matrix[i] = malloc(columns * sizeof(int));
        if (matrix[i] == NULL)
        {
            int k;

            for (k = i - 1 ; k >= 0 ; k--)
                free(matrix[k]);
            free(matrix);

            return -1;
        }

        for (j = 0 ; j < columns ; j++)
        {
            matrix[i][j] = rand() % 100;
            if (matrix[i][j] > largest)
            {
                largestRow    = i;
                largestColumn = j;
                largest       = matrix[i][j];
            }
        }
    }
    swapValue                         = matrix[rows - 1][columns - 1];
    matrix[rows - 1][columns - 1]     = largest;
    matrix[largestRow][largestColumn] = swapValue;

    for (i = 0 ; i < rows ; i++)
    {
        for (j = 0 ; j < columns ; j++)
            printf("%5d", matrix[i][j]);
        printf("\n");
    }

    for (i = 0 ; i < rows ; i++)
        free(matrix[i]);
    free(matrix);

    return 0;
}