Why does this piece of code:
String value = JOptionPane.showInputDialog("Enter x"); //Input = 100
int x = Integer.parseInt(value);
double result = 1;
for (int i = 1; i <= x; i++) //used variable "x" here
{
result += (x * 1.0) / fact(i);
x *= x;
}
public static int fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
work differently from this one?
String value = JOptionPane.showInputDialog("Enter x"); //Input = 100
int x = Integer.parseInt(value);
double result = 1;
for (int i = 1; i <= 100; i++) //and here I used the value "100"
{
result += (x * 1.0) / fact(i);
x *= x;
}
public static int fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
The only change that I made was using the value 100
instead of using the variable x
in my termination expression!
When I run the first code, I get:
9.479341033333334E7
However, for the second one I always get
NaN
Why?