2

仅使用 for 或 while 语句,我试图想出一个程序来生成和打印前 10 个阶乘的表。这是我的代码:

    for (count = 1; count<=10; ++count) 
    {
        n = count;
        while (n > 0){
            count *= (count-1);
            n -= 1;
        }
        NSLog(@"  %2g            %3g", count, factorial);
    }

我不明白为什么这不起作用。它永远不会脱离循环并永远持续下去。修正是什么?谢谢!

4

3 回答 3

4

原因:

count *= (count-1);

由于count从 1 开始,它将始终重置为0,因此count <= 10外部循环的条件将始终为真,因此是无限循环。

无论如何,你把它复杂化了。

for (int i = 1; i <= 10; i++) {
    int r = 1, n = i;
    while (n)
        r *= n--;

    printf("%d! = %d\n", i, r);
}
于 2013-06-04T20:19:14.320 回答
4

在数学中,n!与Γ(n+1) 相同(参见:http ://en.wikipedia.org/wiki/Gamma_function )

所以只需使用:

-(float)factorial:(float)number1 {
    return tgammaf(++number1);
}

这甚至适用于浮点数和负数,

发布的其他解决方案很长且无关紧要,仅适用于正整数。

于 2015-06-05T16:42:26.000 回答
1

在第一个循环迭代期间,计数为 1,因此n也为 1,然后您输入 while 并将count设置为零(count-1),然后将n减小为零并退出 while。所以在第二个循环迭代计数将为零。您不断减少计数并且它永远不会增加,因此您永远不会退出循环,直到发生数字溢出。

你做得比现在更难(而且效率低下)。足以让您继续将n乘以count以获得阶乘:

int n=1;
for (count = 1; count<=10; ++count) 
{
    n*= count;
    NSLog(@"%d",n);
}
于 2013-06-04T20:18:46.863 回答