简体   繁体   中英

Why the place of the assignment of a variable is so important? [C]

While trying to solve an exercise of Kochan - Programming in C Book (ex 4 loops chapter) the question was to write the first 10 factorial numbers. I tried to solve it with nested loops, but the results were a complete rubbish. I looked up, and I found one solution that was very similar to mine but I noticed that the place of the variable is different.

Previous solution:

/*This program calculates the first 10 factorials*/

#include <stdio.h>

int main(void){
    int n,i;
    unsigned long int fact=1;
    printf(" n\t\t  n!\n");
    printf("---\t\t--------\n");
    for(n=1; n<=10; n++){
        for(i = 1; i<=n; i++){
            fact*=i;
        }       
        printf("%2d\t\t%7ld\n",n,fact);
    }

    return 0;
}

Output:

./factorial 
 n        n!
---     --------
 1            1
 2            2
 3           12
 4          288
 5        34560
 6      24883200
 7      857276416
 8      -511705088
 9      1073741824
10            0

Fixed solution:

/*This program calculates the first 10 factorials*/

#include <stdio.h>

int main(void){
    int n,i;
    printf(" n\t\t  n!\n");
    printf("---\t\t--------\n");
    for(n=1; n<=10; n++){
        unsigned long int fact=1;       
        for(i = 1; i<=n; i++){
            fact*=i;
        }       
        printf("%2d\t\t%7ld\n",n,fact);
    }

    return 0;
}

Output:

./factorial 
 n        n!
---     --------
 1            1
 2            2
 3            6
 4           24
 5          120
 6          720
 7         5040
 8        40320
 9       362880
10      3628800

Notice that the only difference is that that variable fact is local in the second solution while it was global in the previous one.

So I guess the question is clarified now, why changing just the place seems to solve the issue? Why there is this issue of placing variables in the first place? Thanks in advance !

因为在n上的每次迭代期间,变量都被设置为1。如果在迭代n的循环开始时将其设置为1,则可以像在第一个代码中一样声明它。 。

The issue is not so much where the variable is declared , as where it is initialized . In the correct code, fact is set to 1 for each new n , in order to "start fresh" and calculate the factorial. In your code, you don't reset fact , so it continues to hold the leftover value from the previous n , so you're computing n! times the previous result.

Another solution is to remove the inner loop, and take advantage of the fact that n ! = n × ( n -1)!. (That will also perform better.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM