Factorial using Addition

后端 未结 4 814
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2021-01-28 14:23

    If you add some intermediate debugging output you'll find where you went wrong:

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

    This produces:

    1 -> num1=5  num2=4  sum=0  j=0
    2 -> num1=5  num2=4  sum=20  j=4
    20
    --------------
    1 -> num1=20  num2=3  sum=20  j=0
    2 -> num1=20  num2=3  sum=80  j=3
    80
    --------------
    1 -> num1=80  num2=2  sum=80  j=0
    2 -> num1=80  num2=2  sum=240  j=2
    240
    --------------
    1 -> num1=240  num2=1  sum=240  j=0
    2 -> num1=240  num2=1  sum=480  j=1
    480
    --------------
    --->480
    

    You can see here that the problem is that the sum value is carried forward from each pass through the loop, when it should really be reset to 0 each time. So add

    sum = 0;
    

    at the top of the while loop.

    So your final code becomes:

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

    Best of luck.

提交回复
热议问题