-2

由于我不精通 C,因此我尝试C 中矩阵转置的第二个示例,仅转换为 JavaScript(下面的代码)。它冻结了浏览器。

有人可以帮助我了解可能导致问题的原因吗?C程序在ideone中运行良好。

正如 Nirk 好心指出的那样,C 程序中的除法是整数而不是浮点数,因此如果不使用Math.floor.

C代码:

#include <stdio.h>

void transpose(double *m, int w, int h)
{
  int start, next, i;
  double tmp;

  for (start = 0; start <= w * h - 1; start++) {
    next = start;
    i = 0;
    do {    i++;
      next = (next % h) * w + next / h;
    } while (next > start);
    if (next < start || i == 1) continue;

    tmp = m[next = start];
    do {
      i = (next % h) * w + next / h;
      m[next] = (i == start) ? tmp : m[i];
      next = i;
    } while (next > start);
  }
}

JavaScript 代码:

function transpose(m, w, h)
{
  var start, next, i,
      tmp

  for (start = 0; start <= w * h - 1; start++) {
    next = start
    i = 0
    do {    i++
      next = (next % h) * w + next / h
    } while (next > start)
    if (next < start || i == 1) continue

    tmp = m[next = start]
    do {
      i = (next % h) * w + next / h
      m[next] = (i == start) ? tmp : m[i]
      next = i
    } while (next > start)
  }
}

function main()
{
  var j
  var m = []
  for (j = 0; j < 15; j++) m[j] = j + 1

  console.log("before transpose:")
  console.log(m)

  transpose(m, 3, 5)

  console.log("\nafter transpose:")
  console.log(m)
}

main()
4

1 回答 1

5

除法是浮点数,不是整数,所以你需要Math.floor(next / h)

于 2013-08-05T01:57:23.147 回答