1

我在 C 中有一些代码:

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

int multiply(int);

int main() {
    FILE *fp;
    int i, j, n, m,
        matrix[99][99],
        sum = 0,
        columnSums[99] = {0};

    fp = fopen("data.txt", "r");
    if(fp != NULL) {
        fscanf(fp, "%d", &n);
        fscanf(fp, "%d", &m);

        for(i = 0; i < n; i++) {
            for(j = 0; j < m; j++) {
                fscanf(fp, "%d", &matrix[i][j]);
            }
        }

        for(i = 0; i < m; i++) {
            for(j = 0; j < n; j++) {
                sum += multiply(matrix[j][i]);
            }
            columnSums[i] = sum;
            sum = 0;
        }
    } else {
        puts("Cannot read the file!");
    }
    puts("");
    system("pause");
    return 0;
}

int multiply(int thisNum) {
    return thisNum * thisNum *thisNum;
}

我的任务要我从文本文件中读取多维数组,然后通过将每个列成员相加乘以自身三倍来对每一列进行排序。读取数组并找到每列添加并将其存储到存储每列添加的其他数组中并不难(希望这会有所帮助),但我坚持将其整理出来。请问有什么建议吗?:)

4

2 回答 2

2

您可以使用 qsort()。不要忘记包含 stdlib.h

#define ARR_SIZE(a) (sizeof(a) / sizeof(*(a)))

int comp(const void* a, const void* b)
{
    return *(const int*)a - *(const int*)b;
}

...

for (i = 0; i < ARR_SIZE(matrix); i++)
{
    qsort(matrix[i], ARR_SIZE(matrix[i]), sizeof matrix[i][0], comp);
}
于 2013-02-18T19:34:29.047 回答
1

您可以使用在 stdlib.h 中声明的 qsort 函数

于 2013-02-18T18:58:22.950 回答