打印 X

打印 X

描述
输入一个正整数N, 你需要按样例的方式返回一个字符串列表。
1≤n≤15

image

【方法一】
#include <iostream>
#include <cstdio>

using namesapce std;

int main() {
    
    int n = 15;
    
    printf("请输入 n 的值:");
    
    while (scanf("%d", &n) != EOF) {
        
        for (int row = 1; row <= n; row++) {
            // 按行处理
            for (int col = 1; col <= n; col++) {
                // 若为正方形对角线上的元素,打印 "X"; 否则为 “ ”
                if (row == col || (n + 1) == (row + col)) {
                    printf("X");
                }else {
                    printf(" ");
                }
            }
            // 接着下一行,开始
            printf("\n");
        }
        
        printf("请输入 n 的值:");
    }
    
    return 0;
}
【方法二】
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>


using namespace std;


int main() {


    vector<string> strArr;

    int n = 5;

    for (int row = 1; row <= n; row++) {
        string str;
        // 按行处理
        for (int col = 1; col <= n; col++) {
           if (row == col || (n + 1) == (row + col)) {
                str += "X";
           }else {
                str += " ";
           }
        }
        strArr.push_back(str);
    }

    int size = strArr.size();

    for (int i = 0; i < size; i++) {
        cout << i + 1 << "-|  " << strArr[i] << endl;
    }

    cout << endl;

    return 0;

}

【方法三】
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>


using namespace std;


int main() {

    vector<string> vecX;
    int n = 5;
    // 假设每行都由 n 个空格组成,在特定的位置再由 'X' 来覆盖
    string str(n, ' ');

    for (int i = 0; i < n; i++) {
        // 在特定位置用 'X',来覆盖
        str[i] = 'X';
        str[n - 1 - i] = 'X';
        vecX.push_back(str);
        // 开始新一行前,重新恢复每行的起始状态
        str[i] = ' ';
        str[n - 1 - i] = ' ';
    }

    int size = vecX.size();

    for (int i = 0; i < size; i++) {
        cout << i + 1 << "-|" << vecX[i] << endl;
    }


    return 0;
}
【结果】
1-|X   X
2-| X X
3-|  X
4-| X X
5-|X   X

Process returned 0 (0x0)   execution time : 0.051 s
Press any key to continue.
posted @ 2022-02-11 20:24  hellozwx  阅读(75)  评论(0编辑  收藏  举报