【问题标题】:Java return command [closed]Java返回命令[关闭]
【发布时间】:2015-04-19 23:58:48
【问题描述】:

所以这里有我从教科书中复制的代码。我不完全理解 factorial(k) 是如何得到它的数字的,因为只有 factorial(n) 有一个计算它的值的方法。

public void run(){
    int n = readInt("Enter the number of objects, n, in the set: ");
    int k = readInt("Enter numberto be chose,k, :");
    println("C("+ n + ", " + k + ") = " + combinations(n, k));
}
private int combinations(int n, int k){
    return factorial(n) / (factorial(k) * factorial(n-k));
}

private int factorial(int n){
    int result = 1;
    for(int i = 1; i <= n; i++){
        result*= i;
    }
    return result;
}

}

【问题讨论】:

  • 什么...?他们称它们为相同的方法,只是输入不同。我对你的困惑感到困惑。编辑:我想我看到了你的困惑。在combinations 中传入的n 与作为factorial 参数的n 相比,是一个完全 不同的变量。请阅读范围!
  • 观察形参和实参之间的区别 - 前者只是一个占位符,具体词汇化在调用站点不起作用!
  • 如果你调用 factorial(3) 调用会去哪里?阶乘(5)去哪儿了?阶乘(n)?想想吧。
  • @collapsar。神圣词汇化蝙蝠侠你刚才说什么?
  • @AndyBrown 无论是调用factorial(n) 还是factorial(k),参数总是映射到private int factorial(int n) 中的n。措辞可能有点过于复杂...... ;-)

标签: java return computer-science


【解决方案1】:

观察参数参数的区别:

return factorial(n) / (factorial(k) * factorial(n-k));

这里的第一个n 是一个参数 - 一个传递给被调用函数的值。

private int factorial(int n)

这里n 是一个参数 - 一个占位符,用于定义函数在使用参数调用时应该做什么。如果你无法表达函数应该用这个参数做什么,那么传递一个参数有什么用?

【讨论】:

【解决方案2】:

你被函数调用和函数定义弄糊涂了。

return factorial(n) / (factorial(k) * factorial(n-k)); 行调用具有不同值(nn-kk)的名为 factorial 的函数。

private int factorial(int n){ 开头的行定义n 的任何给定值的函数。 n 是一个变量,表示调用传递的值。

如果您使用值 10 和 4(分别)调用 combination,那么它会分别使用 10、4 和 6 调用 factorial。第一个调用将 10 绑定到 n(阶乘的形参),第二个 4 绑定到 n(形参),第三个 6 绑定到 n(形参)。

一定义,三用。

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2013-09-30
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2020-02-17
    • 2014-02-12
    相关资源
    最近更新 更多