阶乘/组合在不应该的情况下产生 NaN
我正在求解 y 选择 p 组合。我是 JavaScript 初学者。
我给出了阶乘函数的定义: 它的目的是执行 x * (x-1) * (x-2) ... * 1。
function factorial(z)
{
var product = z;
if (z == 0)
{
return 1;
}
else
{
for (var m = 1; m < z; m++)
{
product = m * product;
return product;
}
}
}
然后我有了这个函数,它使用阶乘函数。
function placeBoxes()
{
var ids = 0;
for (var y = 0; y < (numOfRows-1); y++)
{
for (var p = 0; p < (y+1); p++, ids++)
{
x = document.createElement('div');
x.className = "box";
x.id = ids;
x.innerHTML = (factorial(y))/((factorial(y-p))*(factorial(p)));
document.getElementById('holdsBoxes').appendChild(x);
}
}
}
它应该选择组合。出于实验目的,numOfRows 实际上在 5 到 30 之间。0C0 1C0 1C1 2C0 2C1 2C2 等等... 这相当于 1, 1, 1, 1, 2, 1 等等...
有谁知道我做错了什么?我得到 NaN 而不是第二个、第三个、第五个、第八个、第九个和许多其他值的值。
编辑:谢谢大家!问题解决了。阶乘函数被搞乱了。
I am solving for y Choose p combinations. I am a beginner with Javascript.
I have produced this definition of the factorial function:
It was inteded to do x * (x-1) * (x-2) ... * 1.
function factorial(z)
{
var product = z;
if (z == 0)
{
return 1;
}
else
{
for (var m = 1; m < z; m++)
{
product = m * product;
return product;
}
}
}
I then have this function, which uses the factorial function.
function placeBoxes()
{
var ids = 0;
for (var y = 0; y < (numOfRows-1); y++)
{
for (var p = 0; p < (y+1); p++, ids++)
{
x = document.createElement('div');
x.className = "box";
x.id = ids;
x.innerHTML = (factorial(y))/((factorial(y-p))*(factorial(p)));
document.getElementById('holdsBoxes').appendChild(x);
}
}
}
It is supposed to choose the combinations. For experimental purposes, numOfRows is realistically between 5 and 30. 0C0 1C0 1C1 2C0 2C1 2C2 and so on...
This is equivalent to 1, 1, 1, 1, 2, 1 and so on...
Does anyone know what I have done wrong? I am getting NaN instead of a value for the second, third, fifth, eighth, ninth, and many other values.
Edit: Thank you everyone! The problem is solved. The factorial function was messed up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更改
为
您永远不会完成循环
Change
To
You're never completing the loop
您在循环内返回的
product
。你确定吗?您不想在循环之外返回product
吗?这也是您的
NaN
的原因。如果z
是 1 呢?那么m < z
是m
1
这总是错误的。所以这个循环体永远不会被调用。并且 return 语句永远不会被调用。因此该函数返回
未定义
。并且undefined * 1 === NaN
Your returning
product
inside your loop. Are you sure about this? Don't you want to returnproduct
outside your loop?This is also the cause of your
NaN
. What ifz
is 1 ? thenm < z
ism < 1
and thats always false. So that loop body is never being called. and the return statement is never called.So the function returns
undefined
. Andundefined * 1 === NaN
我认为阶乘函数是不正确的。尝试将其更改为这样:
I believe that the factorial function is incorrect. Try changing it to this: