我正在学习 C++,我的任务是创建数组 [n] [m],用整数填充它,然后
"Characteristic of matrix rows is called the sum of its positive even elements. You need to sort the rows of the matrix in accordance with the growth of characteristics."
这是我的代码
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
int n, m;
cout << "n = ";
cin >> n;
cout << "m = ";
cin >> m;
int ** mas = new int * [n];
for (int i = 0; i < n; ++i)
{
mas[i] = new int[m];
}
cout << "Array:\n";
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
mas[i][j] = rand()%41-20;
cout << mas[i][j] << "\t";
}
cout << "\n";
}
double * characteristic = new double[n];
for (int i = 0; i < n; ++i)
{
characteristic[i] = 0;
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if((j%2 == 0) && (mas[i][j] >= 0))
{
characteristic[i] += mas[i][j];
}
}
}
cout << "Characteristics:\n";
for (int i = 0; i < n; ++i)
{
cout << characteristic[i] << " ";
}
cout << "\n";
for (int i = 0; i < n - 1; ++i)
{
int min = i;
for (int j = i + 1; j < n; ++j)
{
if (characteristic[min] <= characteristic[j]) continue;
min = j;
}
if (min != i)
{
double temp = characteristic[i];
characteristic[i] = characteristic[min];
characteristic[min] = temp;
for (int k = 0; k < m; ++k)
{
int temp1 = mas[i][k];
mas[i][k] = mas[min][k];
mas[min][k] = temp1;
}
}
}
cout << "\nSorted characteristics:\n";
for (int i = 0; i < n; ++i)
{
cout << characteristic[i] << " ";
}
cout << "\n";
cout << "Sorted array:\n";
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cout << mas[i][j] << "\t";
}
cout << "\n";
}
for (int i = 0; i < n; ++i)
{
delete [] mas[i];
}
delete [] mas;
delete [] characteristic;
system("PAUSE");
return 0;
}
我为特征创建了另一个数组,并同时对它和第一个数组进行了排序,但似乎我使用了太难的方法来完成给定的任务。也许还有其他方法?