使用 get 方法计算阶乘



我想用get方法计算一个数字的阶乘(我必须解决一个更大的问题)。这是我尝试过的,它返回1

public Sigma() {
    n = -1;
}
public Sigma(int n) {
    n = n;
}
private int Facto(int n) {
    for (int i = 1; i <= n; i++) {
        result = result * i;
    }
    return result;
}
public int getFacto() {
    return Facto(n);
}

问题是,在构造函数中,您键入n = n而不是this.n = n。这样做的问题是构造函数中的局部变量是赋值的,而不是类的字段。 this.n是指n字段,并且是您想要的。

您收到的输出为 1,因为所有基元数字字段的默认值均为 0 。使用您的代码,0! = 1(这是正确的),因此无论您传递到构造函数中的内容,这就是您的输出,因为构造函数会忽略其参数。

在不相关的说明中,请使用驼峰大小写而不是大写作为方法名称(和字段名称)。大写只能用于类/接口/枚举/注释。此外,result = result * n可以简化为(几乎)等效语句result *= n

对于阶乘,您需要初始化事实函数中的结果,如下所示

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

最新更新