gpt4 book ai didi

java - 如何从 for 循环中返回值?

转载 作者:行者123 更新时间:2023-12-01 08:08:39 27 4
gpt4 key购买 nike

这是我的代码:

import java.util.*;

public class factorialdisplay {
// Main Method. Prints out results of methods below.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);

// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();

for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + factorial(n));
}
}

public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
return f;
}
return f;
}
}

我正在尝试获取输出:

1! = 1 
2! = 2
3! = 6
4! = 24
5! = 120

但是当我运行代码时,我得到了这个:

0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1

我的问题是,如何通过 factorial 静态方法将 for 循环每次迭代的结果返回到 main 方法?

最佳答案

您需要删除 for 循环中的 return f; 语句。 if 中的返回将始终在第一次迭代后立即返回到调用方法。这就是为什么所有阶乘的结果都是 1。

public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
// return f; // Not needed - this is causing the problem
}
return f; // This is your required return
}

Ravi指出

for (int i = 1; i <= n; ++i) { // well 0 will return 1 as well, so no prob unless you don't need 0 factorial
System.out.println(i + "! = " + factorial(i)); // you need to pass i instead of n as i is the counter here
}

关于java - 如何从 for 循环中返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19347621/

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