C++ 生成';魔方';算法(算法来自一本书)
我一直有一个问题,这个神奇的平方码相当长一段时间了。我只是一步一步地遵循一本书的算法,但由于某些原因,它没有正确地显示出来C++ 生成';魔方';算法(算法来自一本书),c++,C++,我一直有一个问题,这个神奇的平方码相当长一段时间了。我只是一步一步地遵循一本书的算法,但由于某些原因,它没有正确地显示出来 intmain(){ int n; 炭温度[100]; 温度; n=原子(温度); 我运行了你的代码,结果如下 Enter an odd number: 5 5 3 1 10 23 6 4 2 11 24 7 16 14 12 25 18 17 15 13 21 19 0 0 0
intmain(){
int n;
炭温度[100];
温度;
n=原子(温度);
我运行了你的代码,结果如下
Enter an odd number: 5
5 3 1 10 23
6 4 2 11 24
7 16 14 12 25
18 17 15 13 21
19 0 0 0 0
我猜编译器之间有些不同。你的问题可能是,负数的模也是负数:
使用负值进行索引是未定义的行为:#包括“stdafx.h”
#包括
#包括
使用名称空间std;
int main()
{
int n;
cout>n;
整数**MagicSquare=新整数*[n];
对于(int i=0;i 对于(int value=0;value FYI),标准不支持使用非常量数组大小:int square[n][n];我很惊讶您可以动态设置超出外部维度的值。添加行cout错误发生在大小为3的地方。使用尽可能小的测试用例以使调试更容易。这是我第二次看到这个确切的问题。这是哪本书?上次发现错误是一场噩梦。@Owl这本书被调用了由Ellis Horowitz和Sartaj Sahni编著的《数据结构基础》。以下是我遵循的算法。
#include "stdafx.h"
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int n;
cout << "Please enter an odd integer: ";
cin >> n;
int** MagicSquare = new int*[n];
for (int i = 0; i < n; ++i)
MagicSquare[i] = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
MagicSquare[i][j] = 0;
}
}
int newRow,
newCol;
// Set the indices for the middle of the bottom i
int i = 0;
int j = n / 2;
// Fill each element of the array using the magic array
for (int value = 0; value <= n*n; value++)
{
MagicSquare[i][j] = value;
// Find the next cell, wrapping around if necessary.
newRow = (i + 1) % n;
newCol = (j + 1) % n;
// If the cell is empty, remember those indices for the
// next assignment.
if (MagicSquare[newRow][newCol] == 0)
{
i = newRow;
j = newCol;
}
else
{
// The cell was full. Use the cell above the previous one.
i = (i - 1 + n) % n;
}
}
for (int x = 0; x<n; x++)
{
for (int y = 0; y<n; y++)
cout << MagicSquare[x][y] << " ";
cout << endl;
}
}