c++ - 创建数字模式

标签 c++

我正在尝试获取这个数字模式

Input: 7 
Output:  
1 1 1 1 1 1 1
1 2 2 2 2 2 1 
1 2 3 3 3 2 1 
1 2 3 4 3 2 1 
1 2 3 3 3 2 1 
1 2 2 2 2 2 1 
1 1 1 1 1 1 1 

但我不知道如何制作它,请问如何制作该图案有什么建议吗??

到目前为止我的代码:

int n, temp1, temp2,i,j;
cin >> n;
for (i = 1; i <= n; i++) {
    for (j = 1; j <= n; j++) {
        temp1 = j;
        temp2 = n-j+1;
        if (temp1 < temp2) cout << temp1;
        else cout << temp2;
    }
    cout << endl;
}

目前的输出是

 1 2 3 4 3 2 1
 1 2 3 4 3 2 1
 1 2 3 4 3 2 1
 1 2 3 4 3 2 1
 1 2 3 4 3 2 1
 1 2 3 4 3 2 1
 1 2 3 4 3 2 1

提前致谢。

最佳答案

我希望这段代码(有效)可以让您对实现有更好的了解。

int main() {

 int n;
 cin >> n;
 int arr[n][n];

//Numbers in the grid vary from  1 - (n/2 + 1)
 for(int i = 0; i <= n / 2; i++) {
    //Start filling the array in squares
    //Like fill the outer square with 1 first followed by 2...
    for(int j = i; j < n - i; j++) {

       arr[i][j] = i + 1;
       arr[n - 1 - i][j] = i + 1;
       arr[j][i] = i + 1;
       arr[j][n - 1 - i] = i + 1;
    }
 }

关于c++ - 创建数字模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638372/

相关文章:

c++ - 将函数参数类型声明为 auto

c++ - 尝试与 boost_timer 链接时出现 DSO 错误

c++ - boost::crc_32_type 会产生任何异常吗?

c++ - 比较 unicode 和 wchar_t C++ : `unable to find numeric literal operator ' operator ""F' `

c++ - 关于在 Linux 中使用管道和守护进程编写聊天室 C 程序有什么建议吗?

javascript - 我如何跟踪 FS 被 emscripten 包含的原因?

c++ - 运营商不匹配>>问题

c++ - mingw-w64 : slow sprintf in <cstdio>

c++ - 什么是 _WIN32_WINNT,它是如何工作的?

c++ - undefined symbol GCC/C++ 可动态加载 *.so 对象