You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++新手实现双字符交替网格打印功能遇阻求解决思路

解决思路
  • 交替字符打印:每行的第j个字符(j从0开始计数)通过(行号 + 列号) % 2的结果判断输出字符,奇数输出char_1,偶数输出char_2,天然满足奇偶行开头字符不同、单字符交替排列的需求。
  • 底部字母标注:所有内容行打印完成后,先输出2个空格对齐上方的行号位置,再从大写字母A开始连续输出width个递增大写字母即可,题目约定宽度不超过26,刚好覆盖A~Z的范围。
  • 注意调整主函数的输入顺序,和示例要求的先输入高度、再输入宽度的逻辑匹配。
完整实现代码
#include <iostream>
#include <string>

using namespace std;

void print_board(int const width,
                int const  height,
                char const char_1,
                char const char_2)
{
    // 打印带行号的交替字符行
    for (int i {1}; i <= height; ++i)
    {
        cout << i << " ";
        for (int j = 0; j < width; ++j)
        {
            cout << ((i + j) % 2 == 1 ? char_1 : char_2);
        }
        cout << endl;
    }
    // 打印底部字母标注
    cout << "  ";
    for (int k = 0; k < width; ++k)
    {
        cout << (char)('A' + k);
    }
    cout << endl;
}
             
int main()
{
    int width {};
    int height {};
    char char_1 {};
    char char_2 {};

    cout << "Input height and width: ";
    cin >> height >> width;
    cout << endl << "Input characters your program should consist of: ";
    cin >> char_1 >> char_2;
    cout << endl;

    print_board(width, height, char_1, char_2);

    return 0;
}

内容的提问来源于stack exchange,提问作者leun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:36:03