简体   繁体   中英

Java program for factorial incorrect output

I am executing the below piece of Java code in Eclipse IDE.

public class Programs {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int i, num, n;
        n = 6;
        // num=n-1;
        for (i = 1; i <= n - 1; i++) {
            n = n * i;
        }
        System.out.println("Factorial of the declared number is" + " " + n);
    }

}

It shows the output as -1420957696. The code works fine if I uncomment and use the "num" variable in the for loop. I think for every iteration the value of n changes gradually incredibly as compared to value of i . The same code works fine in VBScript (see below). Can anyone explain the difference?

Option Explicit
Dim  i, num
num = InputBox("enter a number")
For i=1 To num-1
    num = num * i
Next
MsgBox "The factorial of entered number is: " & num, 3, "Program for factorial"

Java:

n is going to get rather big cf. i .

Therefore i <= n - 1 will always be true , until your n overflows and wraps around to a negative.

One fix would be to use num to hold the original value of n , and use i <= num - 1 as the stopping condition.


VBScript:

In the various basics (Eg VBScript, VBA), num-1 is effectively computed at the start of the loop, and further adjustment to num have no effect on the stopping condition. You can see this explicitly by running

Dim j
Dim i

j = 10
For i = 1 To j
    WScript.Echo i
    j = 1 'has no effect on the stopping condition.
Next

every iteration in the forloop i<=n-1 is checked. Because n is increased all the time, the for loop will run until n reaches the highest possible number of INTEGER and becomes negative.

您没有将先前的乘法存储在另一个变量中,并且您的n总是在增加,因此for for i的条件会在每次迭代时更改。

As mentioned in the above answers evaluation of the condition causes the exception. What you can do is keep a separate variable to check the condition in the loop like this.

int i,fact=1;  
  int number=5;//Number to calculate factorial    
  for(i=1;i<=number;i++){    
      fact=fact*i;    
  }   

it comes down to when numbers are read compared to when they are set:

n = 6;
for (i = 1; i <= n - 1; i++) {
    n = n * i;
}

What java will do is: Set i = 1 , do the check i <= n-1 (1 <= 5) then execute the code in the braces, then increment i ( i++ ). Then this is repeated: i is now equal to 2, do the check i <= n-1 (2 <= 4) n has changed in the last iteration so the check will use the new value. so on the next iteration n = 12 .

This causes n to grow faster than i so when the capacity of an integer is exceeded causing n to go negative the loop condition resolves to false.

The answer is to not modify the value in your loop condition inside the loop.

n = 6;
num = n - 1;
for (i = 1; i <= num; i++) {
    n = n * i;
}

The way the loop is working for VB is by calculating the numbers for the beginning and end of the loop when it is started, meaning that num was only read once.

You are not storing previous multiplication in another variable and your n is always increasing so the condition in for i changes every iteration.

Instead you can have separate variable to hold your factorial .

class FactorialExample{  
 public static void main(String args[]){  
  int i,fact=1;  
  int number=5;//It is the number to calculate factorial    
  for(i=1;i<=number;i++){    
      fact=fact*i;    
  }    
  System.out.println("Factorial of "+number+" is: "+fact);    
 }  
} 


Hope that Helps.

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