Factorial using Addition

后端 未结 4 951
眼角桃花
眼角桃花 2021-01-28 14:19

I am attempting to create a C code that finds the factorial of a integer so that I may convert my code to assembly language. My code seems to \'multiply\' the second integer twi

4条回答
  •  遇见更好的自我
    2021-01-28 14:43

    The steps for the computation are incorrect: it is simpler to start from the low factors to the larger ones.

    Here is a corrected version:

    #include 
    
    #define N 10
    
    int main() {
        int i, j, num1, sum;
    
        num1 = 1;
        sum = 1;
        for (i = 1; i <= N; i++) {
            sum = 0;
            for (j = 0; j < i; j++) {
                sum += num1;
            }
            printf("%d! -> %d\n", i, sum);
            printf("--------------\n");
            num1 = sum;
        }
        return 0;
    }
    

    Output:

    1! -> 1
    --------------
    2! -> 2
    --------------
    3! -> 6
    --------------
    4! -> 24
    --------------
    5! -> 120
    --------------
    6! -> 720
    --------------
    7! -> 5040
    --------------
    8! -> 40320
    --------------
    9! -> 362880
    --------------
    10! -> 3628800
    --------------
    

提交回复
热议问题