由于我不熟悉 C,所以我尝试 this 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()
最佳答案
除法是 float ,不是整数,所以你需要Math.floor(next/h)
关于javascript - 为什么这段 C 代码在 JavaScript 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049577/