-1

我写了这个程序:

#include <stdio.h>

/*Part B

Write a program that:

defines an array of 10 ints
assigns factorial(x) to array element x, for x in the range 0 through 9, inclusive
copies those array elements into a second array of 10 ints, but in reverse order (i.e., element 0 is factorial(9), element 1 is factorial(8), and so on)
prints out that second array to the terminal*/

int factorial(int n){
    int factorial = 1;
    while(n>1){
        factorial = n*factorial;
    }
    return factorial;
}

int main(int argc, char **argv){
    int arr1[10];
    int arr2[10];

    int i = 0;
    for(i = 0; i<10; i++){
        printf("%d", i);
        arr1[i] = factorial(i);
    }

    for(i = 9; i>=0; i--){
        arr2[i] = arr1[9-i];
        printf("%d ", arr2[i]);
    }
    printf("\n");
    return 0;
}

但是当我运行它时,它就坐在那里。我认为这与对阶乘的调用有关,因为当我将其注释掉时,它会立即起作用,但随着它的加入,它甚至没有到达第一个 printf。

我究竟做错了什么?

4

4 回答 4

6
while(n > 1){
    factorial = n*factorial;
}

你错过了n--

于 2012-06-22T14:42:40.207 回答
3

你的while循环:

while(n>1){
    factorial = n*factorial;
}

将永远运行。该循环中没有什么可以改变n的,所以如果进入循环,那么我们知道n将永远大于1n你应该在你的循环中递减:

while(n > 1){
    factorial = n--*factorial;
}

如果您不习惯看到这样的递减,您也可以在新行上执行此操作:

while(n>1){
    factorial = n*factorial;
    n--;
}
于 2012-06-22T14:43:10.807 回答
1

你应该减少n功能factorial

于 2012-06-22T14:43:10.720 回答
1

您对阶乘方法的实现有误。

int factorial(int n){
 int factorial = 1;
 while(n>1){
     factorial = n*factorial;
     n--;
 }
 return factorial;
}

您的代码根本没有对 n 变量做任何事情并保持乘法,而不会减少 n 值。希望这可以帮助

于 2012-06-22T14:47:38.207 回答