C中矩形阵列的2D旋转

时间:2017-11-25 13:35:44

标签: c rotation 2d transform

我正在尝试用c中的2d数组操作。特别是2d形状的原位旋转,所以我做了我的研究并想出了:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAD(x) ((x) * 3.14 / 180)

char shape[3][3] = {{1, 1, 1},
                    {1, 0, 1},
                    {1, 1, 1}};

char nf[5][5]= {{0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0}};

char expa[5][5]= {{0, 0, 1, 0, 0},
                  {0, 1, 0, 1, 0},
                  {1, 0, 0, 0, 1},
                  {0, 1, 0, 1, 0},
                  {0, 0, 1, 0, 0}};

void print(int row, int col, char shapein[][col]) {
  for (int i = 0; i < row; ++i) {
    for (int j = 0; j < col; ++j) {
      printf("%c", ((shapein[i][j]) == 1) ? '#' : ' ');
    }
    printf("\n");
  }
}

void main() {
  int nw = 5;
  int nh = 5;

  int xf = nw / 2;
  int yf = nh / 2;
  float angle = RAD(90);


  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 3; ++j) {
      int nx = ((i - xf) * cos(angle) - (j - yf) * sin(angle)) + xf;
      int ny = ((i - xf) * sin(angle) + (j - yf) * cos(angle)) + yf;

      nf[nx][ny] = shape[i][j];
    }
  }

  print(5, 5, nf);
}

我希望得到这样的输出:

OK output

然而,我得到的是:

Wrong output

我做了我从研究中得到的理解:   - 旋转确实发生在原点(假设左上角)   - 移动的坐标,使其处于原始尺度。   - 旋转时将输出数组的尺寸用作空间。

我很难过,我需要一些帮助。 在它的时候,正如你从我的代码中看到的那样,我对新的旋转尺寸进行了硬编码, 但是,如果有人可以指导我如何动态计算新的旋转尺寸,而不使用“最大角落”方法,那将是很好的。

1 个答案:

答案 0 :(得分:1)

  1. 您展示的预期结果看起来像shape旋转了45º,但您将角度设置为90º。

  2. 您正在使用整数坐标但使用浮点函数。 sincos例程必须返回近似值,并且当浮点值转换为整数时,它们将被截断。您可能更喜欢舍入,可能使用round函数。

  3. xfyf似乎使用nw / 2nh / 2设置为图像的中心,但它们是整数,因此结果为2在每种情况下,距离实际中心相当远,2.5。

  4. 可能存在其他错误,但您应该修复这些错误并继续工作。另外,请采取措施调试代码。在循环内部,打印xfyfnxny的每个值,以便您可以查看计算的输入和输出。手动检查它们是否正确。如果它们不对,请检查各个计算以查看它们正在做什么。

相关问题