奥数与C++小学三年级(第六题-空心棋子)

第六题空心棋子代码:

#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;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值