第六题空心棋子代码:
#include <iostream>
using namespace std;
int main() {
// 最外层每边围棋子数
int outerEdge = 14;
// 计算三层空心方阵的围棋子总数
int totalChessPieces =
// 最外层
(outerEdge * 4 - 4) +
// 第二层,每边减少2个
((outerEdge - 2) * 4 - 4) +
// 第三层,再减少2个
((outerEdge - 2 * 2) * 4 - 4);
cout << "晶晶摆这个三层空心方阵共用了围棋子:" << totalChessPieces << "个。" << endl;
return 0;
}
第六题拓展n层代码:
#include <iostream>
using namespace std;
int main() {
int m, n; // m 是最外层每边的棋子数,n 是层数
// 获取用户输入
cout << "请输入最外层每边的棋子数 m: ";
cin >> m;
cout << "请输入层数 n: ";
cin >> n;
// 检查层数是否合理
if (m - 2 * (n - 1) < 1) {
cout << "层数n过大,导致内层无法形成完整的边。" << endl;
return 1; // 非法输入,退出程序
}
// 初始化总数为0
int totalChessPieces = 0;
// 逐层计算并累加
for (int i = 1; i <= n; ++i) {
int sideChessPieces = m - 2 * (i - 1); // 当前层每边的棋子数
// 如果当前层只有1个或0个棋子在边上,则不需要减去4个角点
if (sideChessPieces <= 1) {
totalChessPieces += sideChessPieces * 4; // 直接乘以4,因为没有重复的角点需要减去
} else {
totalChessPieces += sideChessPieces * 4 - 4; // 减去4个重复的角点
}
}
// 输出结果
cout << "摆这个" << n << "层空心方阵(最外层每边" << m << "个棋子)共需围棋子:" << totalChessPieces << "个。" << endl;
return 0;
}