#include \n#include \nusing namespace std;\nint main()\n{\n int n;\n cin >> n;\n if (n % 2 == 0 || n > 17)\n {\n cout << "Invalid input" << endl;\n return 0;\n }\n \n int ans[20][20] = {0};\n int x = 1, y = (n + 1) / 2;\n for (int i = 1; i <= n * n; i++)\n {\n int newX = (x + 2 - 1) % n + 1;\n int newY = (y + 1 - 1) % n + 1;\n if (ans[newX][newY] == 0)\n {\n x = newX;\n y = newY;\n }\n else\n {\n x = (x + 1 - 1) % n + 1;\n }\n ans[x][y] = i;\n }\n \n for (int i = 1; i <= n; i++)\n {\n for (int j = 1; j <= n; j++)\n {\n cout << setw(4) << ans[i][j];\n }\n cout << endl;\n }\n \n return 0;\n}

C++ 奇数幻方算法代码优化:解决输入验证、初始化和索引错误

原文地址: https://www.cveoy.top/t/topic/p9BJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录