Java program for factorial incorrect output
I execute the following java code in the 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 displays the output as - 1420957696 If I uncomment and use the "num" variable in the for loop, the code works properly I think for each iteration, the value of N changes gradually compared with the value of I The same code works in VBScript (see below) Can anyone explain the difference?
Option Explicit
Dim i,num
num = Input@R_676_2419@("enter a number")
For i=1 To num-1
num = num * i
Next
Msg@R_676_2419@ "The factorial of entered number is: " & num,3,"Program for factorial"
Solution
Java:
N will become quite large I
Therefore, I < = n - 1 will always be true until your n overflows and winds back to a negative number One solution is to use num to save the original value of N and use I < = num - 1 as the stop condition In VBScript: in various basic knowledge (such as VBScript, VBA), num-1 is effectively calculated at the beginning of the cycle, and further adjustment of num has no effect on the stop condition You can see this clearly 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
