I found something strange in the factory calculation, so I'm asking you a question!

Asked 2 years ago, Updated 2 years ago, 133 views

1.

#include <stdio.h>

int main(void){
    int a,i;

    scanf("%d",&a);

    for(i=1; i<a; i++)
    {
        a = a*i;
    }

    printf("%d",a);

    return 0;
}

2.

#include <stdio.h>

int main(void){
    int a,i;

    scanf("%d",&a);

    for(i=a-1; i>0; i--)
    {
        a = a*i;
    }

    printf("%d",a);

    return 0;
}

If both inputs are 5 There is no difference in multiplying code 1 and code 2 by 5 to 1, but the result is different
The first code is -1899959296 Code number 2 normally comes out at 120, but I don't know why, so I'm asking you this question!

factorial for

2022-09-22 18:32

1 Answers

Just in case, I searched -189959296 and there was already a stack overflow question that was exactly the same as you were asking

int a = 5;
for (i=1; i<a; i++) { // <-- A
   a = a*i;           // <-- B
}                     }                     // <-- C

This for will be circulated as follows:

As you can see, this loop can never reach C because a in the for statement is constantly changing. So it's too big, and the expression is -189959296. (There seems to be something about maxValue, but I don't know C from here, so I'll skip it.)

Make sure that the following code is working properly.

#include <stdio.h>
int main(void) {
    int a, factorial;
    a = 5;
    factorial = a;
    // Now a is not changed while the next for is traversed.
    for (int i = factorial - 1; i > 0; i--) {
        // Only the value factor to be returned is changed by the loop.
        factorial *= i;
    }
    // Output: 120 (= 5 * 4 *...) * 1)
    printf("%d", factorial);
    return 0;
}

Lesson: If you get an unexpected result, copy it and put it in Google, thinking, "No way.


2022-09-22 18:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.