Factorial loop results are incorrect after the 5th iteration

前端 未结 4 2086
离开以前
离开以前 2021-01-19 07:38

I am currently taking pre-calculus and thought that I would make a quick program that would give me the results of factorial 10. While testing it I noticed that I was gettin

4条回答
  •  既然无缘
    2021-01-19 08:02

    In addition to what the other answers mention about the overflow, your factorial algorithm is also incorrect. 10! should calculate 10*9*8*7*6*5*4*3*2*1, you are doing (10*9)*(9*8)*(8*7)*(7*6)*...

    Try changing your loop to the following:

    int x = 1;
    for(int n = 10; n > 1 ; n--)
    {
        x = x * n;
        System.out.printf("%d ", x);
    }
    

    You will eventually overflow if you try to calculate the factorial of higher numbers, but int is plenty large enough to calculate the factorial of 10.

提交回复
热议问题