我在显示幻方中每一行和每一列的总和时遇到困难。我的幻方算法很好,但是当我试图显示每一边的总和时,它有点搞乱了我的幻方,它给了我很大的负值。我有一种预感,这与我的索引有关,我花了很多时间来弄清楚为什么我不能正确显示它。任何帮助将不胜感激。
魔方是 nxn 矩阵中从 1 到 n^2(n 平方)的数字排列,每个数字恰好出现一次,并且任何行、任何列的元素之和,或任何主对角线是相同的。不难证明这个和一定是n(n^2+1)/2。
要解决这个问题,请将 1 放在正方形的第一行中间,然后对于下一个数字,向上移动然后向左移动,如果索引已被占用,则将其放在下一行。
抱歉我不太会用英文解释。谢谢
#include <iostream>
using namespace std;
int main(){
int n,x,y;
cout<<"Enter size of the magic square " <<endl;
cout<<"Must be odd number starting from 3: ";
cin>>n;
while(n%2==0){ //condtion if the entered value is even
cout<<"Please Enter Odd number: ";
cin>>n;
}
cout<<"\n\n";
int array[n][n]; //create 2d matrix
for( x=0;x<n;x++){ //initialize the value of your 2d matrix as 0
for( y=0;y<n;y++){
array[x][y] = 0;
}
}
int row = 0; //your row starting position
int col = n/2; //your colum starting position
array[row][col] =1; //position of your first counting number
for (int i = 2; i <= n*n; ++i) //this is working algorith is up left
{
if((i-1)%n == 0) //if it is occupied go down
{
row++;
}
else
{
row--;
row = (row+n)%n;
col -=1;
col%=n-1;
}
if (col<0){
col = col+n;
}
array[row][col] = i;
} //up to here
for(x=0;x<n;x++){ //display sum in the side
for(y=0;y<n;y++){
array[x][n]+=array[x][y];
}
}
for(x=0;x<n;x++){ //display sum at the bottom
for(y=0;y<n;y++){
array[n][x]+=array[x][y];
}
}
for(x=0;x<=n;x++){ //display your matrix.
for(y=0;y<=n;y++){
cout<<"\t" <<array[x][y] <<" ";
}
cout<<"\n\n";
}
}
最佳答案
使用
int array[n][n]; //create 2d matrix
作为扩展仅在某些平台上受支持。我强烈建议将其更改为使用 std::vector
。
std::vector<std::vector<int>> array;
此外,您使用:
array[n][x]+=array[x][y];
和
array[x][n]+=array[x][y];
这些行会导致未定义的行为,因为 n
不是有效索引。
此外,在这两种情况下,您都在累积行中的值。第二行需要累加列中的值。您需要使用 array[y][x]
。
您想将行的总和和列的总和显示为最终输出以及二维数组的元素。为此,创建一个 n+1 X n+1
矩阵会更容易。您可以使用:
std::vector<std::vector<int>> array(n+1, std::vector<int>(n+1));
计算行总和并将它们存储在第 n+1
列的逻辑需要是:
for(x=0;x<n;x++){
array[x][n] = 0;
for(y=0;y<n;y++){
array[x][n] += array[x][y];
}
}
计算列总和并将它们存储在第 n+1
行的逻辑需要是:
for(x=0;x<n;x++){
array[n][x] = 0;
for(y=0;y<n;y++){
array[n][x] += array[y][x];
}
}
在 https://ideone.com/XBzUr0 查看它的工作情况.
关于c++ - 显示二维数组中两边的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859909/