简体   繁体   中英

can't get expected output to this “Factorial” program?

My name is sam and i'm a beginner in java.I have actually tried this "factorial" program on my own and i can't see whats going wrong with logic....I'm not getting the expected output,can anyone tell me why? Thanks in advance,grt day to all the users :)

Factorial:

import java.util.*;

class factorial {

    public static void main(String[] args) {

        int i;

        System.out.println("enter a number");

        Scanner in=new Scanner(System.in);

        int n=in.nextInt();

        int x=n;

        while(x!=0) {
            x=x*(n-1);
            n--;
        }

        System.out.println(x);

    }

}

When I enter (for example) 5, I expect to get the factoial of 5 (120). Instead, I get zero. This happens for all inputs.

If you really want to learn, start running code in your head, line by line, such as with:

int n = 5;

int x = n;
while (x != 0) {
    x = x * (n - 1);
    n--;
}

Start with a sheet of paper thus:

  x  |  n
-----+-----
     |
     |
     |
     |

and, as you "execute" each line, write down the new values. Do that and it will be immediately obvious where your problem lies. It will also make you a better developer.

Please do not look at the rest of this answer until you have done that, and tried to fix it.


Once you've understood the problem and (hopefully) fixed it, compare what you have with the solution below:

int n = 5;          // input value.

int x = 1;          // initial accumulator set to identity (n * 1 = n).
while (n != 0) {    // use all values from n down to 1 (inclusive).
    x = x * n;      // multiply accumulator by that value.
    n--;            // get next value.
}

int x=n;

    while(x!=0) {
        x=x*(n-1);
        n--;
    }

The result will be 0 because your loop will work for ever until x=0, x get the value of 0 in your loop when n becomes 0, try n!=0 in while loop condition

You simply need to change the While loop condition to while(n!=1), because in your case when n becomes 1 then x=x*(n-1); will result in x being multiplied with 0.

Try out this code:

 public static void main(String[] args)

{

    int i;

    System.out.println("enter a number");

    Scanner in=new Scanner(System.in);

    int n=in.nextInt();

    int x=1;

    while(n!=0)

    {

        x*=(n);
        n--;

    }

    System.out.println(x);

}

Your while loop is multiplying your answer by 0 when n=1, and we all know what multiplying by 0 does.

EDIT: My bad, edited code.

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