【发布时间】:2020-10-01 11:59:40
【问题描述】:
我仍在尝试使用指针向函数传递/返回数组,或者它也称为动态数组?
我仍然不清楚如何以这种方式传递数组/返回数组(请解释)
而且我真的无法在网上找到解决方案。我尝试使用在线可用的材料来编写代码,但似乎没有任何效果。
在我下面的代码中,程序应该调用makeMS 函数来创建一个 n x n 幻方 (ms),n 大小由用户指定,然后应该返回。
之后,ms 数组将被传递给printTable 函数以打印数组元素。
isMagicSquare 将获取数组并检查所有行、列和对角线是否具有相同的和(魔术常数)。
拜托,任何帮助都会很棒
#include <iostream>
#include <iomanip>
#include <cstring>
int i, j, n, num;
using namespace std;
//Function to check if array is a magic square or not
bool isMagicSquare (int **magicSquare, int n) {
//get the sums of the 2 diagonals if the sum is the same
int sum1 = 0, sum2 = 0;
for (i = 0; i < n; i++) {
sum1 += magicSquare[i][i];
}
for (i = 0; i < n; i++) {
sum2 += magicSquare[i][n-1-i];
}
if(sum1 != sum2)
return false;
//Now for the sums of rows
for ( i = 0; i < n; i++) {
int rowSum = 0;
for (j = 0; j < n; j++) {
rowSum += magicSquare[i][j];
}
if (rowSum != sum1)
return false;
}
//sum of the columns
for ( i = 0; i < n; i++) {
int colSum = 0;
for (j = 0; j < n; j++) {
colSum += magicSquare[j][i];
}
if ( sum1 != colSum )
return false;
}
return true;
}
// Print magic square
void printTable (int **magicSquare, int n) {
cout << "The Magic Square for n=" << n << ":\nSum of "
"each row or column " << n * (n*n+1) / 2 << ":\n\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
cout << setw(5) << magicSquare[i][j] << " ";
cout << endl;
}
}
//Function that constructs the magic square
int **makeMS (int n) {
int **tableArr = new int*[n];
//makes all slots 0
memset(tableArr, 0, sizeof(tableArr));
//Position of 1st number
i = 0;
j = n/2;
//Step to magic square construction
for (num = 1; num <= n*n;) {
//if the position of k + 1 is tableArr[-1][n], 3rd condition
if ( i == -1 && j == n) {
j -= 1;
i += 2;
}
else {
if (j == n) {
j = 0;
}
if(i < 0) {
i = n - 1;
}
}
//3rd condition (occupied slot)
if (tableArr[i][j]) {
i+= 2;
j -= 1;
continue;
}
else {
tableArr[i][j] = num++; //set number
j++; i--; //1st step
}
}
return tableArr;
}
int main () {
int sum;
int **magicSquare;
cout << "Please enter size of array [n] \n";
cin >> n;
if(n%2) {
magicSquare = makeMS(n);
}
else
cout << "Please enter an odd no for the array size";
printTable(magicSquare, n);
if (isMagicSquare(magicSquare, n)) {
cout << "\n \nThe Matrix/Array is a Magic Square \n\n" ;
}
else {
cout << "\n The Matrix/Array is NOT a Magic Square";
}
}
【问题讨论】:
-
您是想了解 C++ 中的多维数组,还是不关心实现细节而只想要一个矩阵数据结构来解决您实际解决的任何问题?如果是后者,只需使用
std::vector<std::vector<int>>并开心就好。 -
tableArr被空指针填充,你需要分配它们。你真的需要使用原始数组吗?std::vector会更简单更安全
标签: c++ arrays function pointers