开发者

A program which calculate factorial from 1-9 by iteration

开发者 https://www.devze.com 2023-04-06 20:10 出处:网络
I am trying to write a program which can calculate factorial from 1-9 by iteration, but I encounter some problems while I am trying to. Please help me figure out my problems in my program, I am just l

I am trying to write a program which can calculate factorial from 1-9 by iteration, but I encounter some problems while I am trying to. Please help me figure out my problems in my program, I am just learning programming.

The following is my program, please tell me what's wrong with it:

public class iterative {
    static int ans=1;
    public static void iteration() {
        System.out.println("n n!");

        for (int n=1; n<10; n++) {
            while ((n-1)>0)
                ans=n*(n-1);
            System.out.println(n + " " + ans);
        }

   开发者_JAVA百科 }


    public static void main(String[] args) {
        iteration();
    }
}


First of all, don't use a static for ans. A local is what you want.

Secondly the factorial recurrence relationship you use is incorrect. You should do it like this.

int ans = 1;
for (int n=1; n<=9; n++) {
    ans = ans*n;
    System.out.println(n + " " + ans);
}


The answers above is close perfect,you also get it with the recursion: here is code:

public class iterative {

    public static int iteration(int n) {
        int result;
        if(n==1)return n;
        else
        result = n*iteration(n-1);
     return result;
    }


    public static void main(String[] args) {
        System.out.println("Result is :" + iteration(9));
    }
}


I see three big problems.

Firstly, "ans" is global and is never reassigned. So over time it will display an accumulated incorrect value.

The other is that the while loop will run forever for n > 1.

Lastly, the recurrence relationship is wrong. Should be ans = ans * (n-1). See code.

The fact that you have nested loops suggests to me that you are trying to print a table of factorials.

Try this:

for (int n=1; n<10; n++) {
    int ans = 1;
    int x = 0;
    while ((n-x)>0){
        ans=ans*(n-x);
        x++;
    }  
    System.out.println(n + " " + ans);
 }


Like @David's solution but shorter

for(int i=1, ans=1; i <= 9; i++, ans *= i)
   System.out.println(i + " " + ans);


Your algorithm needed work as well:

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
         int i = 1;
         while(i < 10)
            iteration(i++);
    }

    public static void iteration(int max) {
        System.out.println("n n!");
        int ans = 1;
        for (int n=1; n<=max; n++) {
            ans *= n;       
      }
      System.out.println(" " + ans);
}

ideone example

0

精彩评论

暂无评论...
验证码 换一张
取 消