What's the difference when using numeric literal in termination expression of a for statement?

扶醉桌前 提交于 2019-12-10 23:34:44

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/32040930/whats-the-difference-when-using-numeric-literal-in-termination-expression-of-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!