2

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?

durron597
  • 31,968
  • 17
  • 99
  • 158
  • 1
    Well, because x changes mid-loop in the first one. – elixenide Aug 16 '15 at 23:30
  • You might want to throw a comment in there to point at where the difference is. People whip through these questions, so it's in your interest to make your issue jump out at readers. – Adrian Aug 16 '15 at 23:30

1 Answers1

2

The difference between the two snippets is this:

for (int i = 1; i <= x; i++) {

vs.

for (int i = 1; i <= 100; i++) {

In the first case, x gets much larger every time! Eventually, it will stop when x overflows and becomes 0, which will be much sooner than in the second case. For an explanation as to why this results in 0 instead of some other random number, see: Why does this multiplication integer overflow result in zero?

In the second case, when i = 34, fact(n) will return 0, so the double division is (0 * 1.0) /0 which results in NaN. Any double, when added to NaN, becomes NaN, which is why the second snippet results in NaN. See: In Java, what does NaN mean?

Community
  • 1
  • 1
durron597
  • 31,968
  • 17
  • 99
  • 158