gpt4 book ai didi

java - 在 for 语句的终止表达式中使用数字文字有什么区别?

转载 作者:行者123 更新时间:2023-11-30 08:48:18 24 4
gpt4 key购买 nike

为什么这段代码:

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;
}

与这个工作方式不同?

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;
}

我所做的唯一更改是在我的终止表达式中使用值 100 而不是使用变量 x!

当我运行第一个代码时,我得到:

9.479341033333334E7

然而,对于第二个,我总是得到

NaN

为什么?

最佳答案

这两个片段的区别在于:

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

对比

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

在第一种情况下,x 每次都会变大!最终,它会在 x overflows 时停止。并变为 0,这将比第二种情况快得多。有关为什么这会导致 0 而不是其他随机数的解释,请参阅:Why does this multiplication integer overflow result in zero?

第二种情况,当i = 34时,fact(n)会返回0,所以双除法是(0 * 1.0)/0 结果为 NaN。当添加到 NaN 时,任何 double 都会变成 NaN,这就是第二个代码片段生成 NaN 的原因。请参阅:In Java, what does NaN mean?

关于java - 在 for 语句的终止表达式中使用数字文字有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com