【问题标题】:Calculating factorial with get method用get方法计算阶乘
【发布时间】:2016-03-05 15:22:03
【问题描述】:

我想用 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);
}

【问题讨论】:

标签: java factorial


【解决方案1】:

问题在于,在您的构造函数中,您输入的是n = n 而不是this.n = n。这样做的问题是分配了构造函数内的局部变量,而不是您的类的字段。 this.n 指的是n 字段,是你想要的。

您收到1 的输出,因为所有原始数字字段的默认值为0。使用您的代码0! = 1(这是正确的),因此无论您将什么传递给构造函数,这都是您的输出,因为构造函数会忽略其参数。

在不相关的注释中,请使用 camelCase 而不是 UpperCase 作为方法名称(和字段名称)。 UpperCase 应该只用于类/接口/枚举/注解。此外,result = result * n 可以简化为 (almost) 等效语句 result *= n

【讨论】:

    【解决方案2】:

    对于阶乘,你需要在facto函数中初始化result,像这样

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

    【讨论】:

    • 我很确定(尽管问题需要澄清这一点)要么发生此分配但未显示,要么result 是分配给1 的字段,因为没有提到编译错误关于意外令牌 (result)。真正的问题在于构造函数(见我的回答)。
    猜你喜欢
    • 2013-02-19
    • 1970-01-01
    • 2010-12-17
    • 2022-01-17
    • 1970-01-01
    • 2023-03-22
    • 2015-04-19
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多