0

这是我的代码:

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

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

4

4 回答 4

4

您需要删除循环中的return f;语句。for中的返回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
}

正如拉维指出的那样

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
}
于 2013-10-13T16:44:05.813 回答
1

代码的三个问题:

  1. 开始于i = 1
  2. factorial(i)不打电话factorial(n)

    for (int i = 1; i <= n; ++i) { // (1) start at i = 1
      System.out.println(i + "! = " + factorial(i)); // (2) pass i not n
    }
    
  3. 返回一次;循环结束后

    for (int i = 1; i <= n; ++i) {
      f *= i;
      // return f; // (3) don't return from here
    }
    return f;
    
于 2013-10-13T16:49:24.623 回答
1

不要回到这里:

for (int i = 1; i <= n; ++i) {
  f *= i;
  return f; // here!
}

而是在循环结束时。您需要在循环的所有迭代中累积最终结果。

于 2013-10-13T16:45:03.557 回答
0

嗯......你有点想到一个yield操作(在某些语言中可用,但不是Java)。yield是一个结构,它说:“从函数中返回一个值,但将我当前所在的位置加入书签,然后让我稍后再回来”。return另一方面说“返回价值并丢弃我所做的一切”。在 Java 中,您不能“暂停循环”并稍后再返回。

我不明白你想要实现的不是通过重复计算来浪费时间(并且仅仅留下其他答案中提出的回报对性能非常不利;只是尝试一些更大的数字......)。您可以通过不产生结果而是将它们存储在数组中来实现它。像这样:

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();

int[] results = factorials(n);
for (int i = 0; i <= n; ++i) {
  System.out.println(i + "! = " + results[i]);
}

和功能:

public static int[] factorials (int n) {
  int[] results = new int[n + 1];
  results[0] = 1;

  int f = 1;
  for (int i = 1; i <= n; ++i) {
    f *= i;
    results[i] = f;
  }
 return results;

}

请注意,上面的内容可以写得更好——我尝试尽可能少地修改您的代码。

于 2013-10-13T17:00:19.987 回答