【发布时间】:2019-01-06 02:10:35
【问题描述】:
我正在尝试根据最后一列的值按降序对二维数组进行排序。我的代码如下:
#include <stdio.h>
#define totrow 10
#define totcolumn 6
float grade[totrow][totcolumn];
void reArg (float grade[][totcolumn]);
void reArg (float grade[][totcolumn])
{
int temp, x, k = 5;
for (int r = 0; r < totrow; r++)
{
for (int c = 0; c <totcolumn;c++)
{
if (grade[r][k] > grade[c][k])
{
for(x = 0; x < totcolumn;x++)
{
temp = grade[r][x];
grade[r][x]=grade[c][x];
grade[c][x]=temp;
}
}
}
}
for (int r = 0; r < totrow; r++)
{
for (int c = 0; c < totcolumn; c++)
{
printf("%.2f\t",grade[r][c]);
}
printf("\n");
}
}
代码编译后,我的数组得到了这个:
7899.00 92.00 90.00 88.00 86.00 89.00
6814.00 85.00 86.00 92.00 88.00 87.00
8234.00 77.00 87.00 84.00 98.00 86.00
7654.00 76.00 87.00 84.00 88.00 83.00
3534.00 86.00 81.00 84.00 73.00 81.00
7284.00 56.00 81.00 87.00 98.00 80.00
9901.00 45.00 78.00 79.00 80.00 70.00
6465.00 87.00 54.00 68.00 72.00 70.00
7934.00 76.00 91.00 84.00 65.00 79.00
7234.00 76.00 81.00 84.00 78.00 79.00
原始数组是:
6814.00 85.00 86.00 92.00 88.00 87.75
7234.00 76.00 81.00 84.00 78.00 79.75
6465.00 87.00 54.00 68.00 72.00 70.25
7899.00 92.00 90.00 88.00 86.00 89.00
9901.00 45.00 78.00 79.00 80.00 70.50
8234.00 77.00 87.00 84.00 98.00 86.50
7934.00 76.00 91.00 84.00 65.00 79.00
7284.00 56.00 81.00 87.00 98.00 80.50
7654.00 76.00 87.00 84.00 88.00 83.75
3534.00 86.00 81.00 84.00 73.00 81.00
为什么程序只排序前 6 行?
【问题讨论】:
-
如果您更改为
#define totrow 9 #define totcolumn 5进行实验会怎样? -
原始数组丢失了最后两个值。
-
您的代码至少有一个
}似乎不完整(假设我的编辑没有错误),请让显示的代码可编译,创建一个minimal reproducible example。 -
你说得对,最后一行应该有一个 } 我没有在我的帖子中包含它。该代码确实在我的编译器上编译,它会打印结果。我相信问题出在 if 语句中,因为 r 最终会小于 c。
-
“它将打印结果”我对此表示怀疑,没有
main()并且没有任何数组中的值。请创建一个minimal reproducible example 来展示您的观察结果。
标签: c arrays sorting multidimensional-array columnsorting