使用数组创建数字模式

时间:2016-11-20 04:36:02

标签: c++ arrays numbers

所以数字模式是这样的:

Input    : 2
Output   : 
            0  0  0  1  0   0  0
            0  0  2  0  12  0  0
            0  3  0  0  0   11 0
            4  0  0  0  0   0  10
            0  5  0  0  0   9  0
            0  0  6  0  8   0  0
            0  0  0  7  0   0  0

我已经使用常规方法解决了它,但是当我尝试使用数组时,输出真的搞砸了。有关如何使用数组创建此数字模式的任何建议吗?

这是我创建此数字模式的代码:

int input, n, mid, i, j;
cin >> input;

n = (2*input)+3;
mid = (n+1)/2;

for(i = 1; i <= n; i++) {
    for (j = 1; j <= mid; j++) {
        if (i <= mid && j == mid-i+1) cout << i << " ";
        else if (i > mid && j == mid-n+i) cout << i << " ";
        else cout << "0 ";
    }
    for (j = mid+1; j <= n; j++) {
        if (i >= mid && j == n+mid-i) cout << (2*n-i) << " ";
        else if (i < mid && j == mid+i-1) cout << (2*n-i) << " ";
        else cout << "0 ";
    }
    cout << endl;
}

提前致谢。

2 个答案:

答案 0 :(得分:1)

我认为此代码(正常工作)可能会对您有所帮助。

#include<iostream>
#include<stdio.h>
#include<string.h>

using namespace std;

int main() {

   int input, n, mid, i, j;
   cin >> input;

   n = (2*input)+3;
   mid = (n+1)/2;

   int arr[n][n];
   memset(arr, 0, sizeof(arr));

   for(i = 1; i <= n; i++) {
     for (j = 1; j <= mid; j++) {
        if (i <= mid && j == mid-i+1) arr[i - 1][j - 1] = i;
        else if (i > mid && j == mid-n+i) arr[i - 1][j - 1] = i;
   }
   for (j = mid+1; j <= n; j++) {
      if (i >= mid && j == n+mid-i) arr[i - 1][j - 1] = 2 * n - i;
      else if (i < mid && j == mid+i-1) arr[i - 1][j - 1] = 2 * n - i;
   }
}

}

答案 1 :(得分:1)

补充baymaxx,如果你想要动态内存分配:

   #include <iostream>
   #include <stdio.h>
   #include <string.h>

   int input, n, mid, i, j;
   cin >> input;

   n = (2*input)+3;
   mid = (n+1)/2;

   // create array of the specified size.
   int** arr = (int**) malloc (n * sizeof(int**));
   for (int p = 0; p < n; ++p) {
       arr[p] = (int*) malloc(n * sizeof(int));
       for (int q = 0; q < n; ++q) {
           arr[p][q] = 0;
       }
   }

   // fill array (algorithm attr. baymaxx)
   for(i = 1; i <= n; i++) {
     for (j = 1; j <= mid; j++) {
        if (i <= mid && j == mid-i+1) {
            arr[i - 1][j - 1] = i;
        }
        else if (i > mid && j == mid-n+i) {
            arr[i - 1][j - 1] = i;
        }

       }
       for (j = mid+1; j <= n; j++) {
           if (i >= mid && j == n+mid-i) {
              arr[i - 1][j - 1] = 2 * n - i;
           }
            else if (i < mid && j == mid+i-1) {
              arr[i - 1][j - 1] = 2 * n - i;
          }
       }
   }

   // print array
   for (int p = 0; p < n; ++p) {
       for (int q = 0; q < n; ++q) {
           int x = arr[p][q];
           std::cout << x << " ";
       }
       std::cout << endl;
   }

   // delete array
   for (int i = 1; i < n; ++i) {
       free(arr[i]);
   }
   free(arr);