当前位置:编程学习 > JAVA >>

设n为自然数,分别求出n=0,2,4,6,8的阶乘

大家好,我是初学者,今天在书上看见这样一个题目,我安装书上的代码敲上去,却出现错误。请问大家这是怎么回事,该如何解决呢,谢谢大家。
代码如下:
public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Factorial ff=new Factorial();
for (int i = 0; i < 5; i++) {
ff.setInitVal(2*(i+1));
ff.result=Factorial(ff.initval);
ff.print();
}
}
public static int Factorial(int n){
if (n==0) {
return 1;
}
return n*Factorial(n-1);
}
} --------------------编程问答-------------------- 递归的算法..具体错误贴出来哦 --------------------编程问答-------------------- Factorial ff=new Factorial(); 这行错了..
修改成:
Test  tt = new Test();
就可以了. --------------------编程问答-------------------- 可运行代码如下: 


public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
Test ff = new Test();
for (int i = 0; i < 5; i++) {
int sum = Factorial(2 * (i + 1));
System.out.println(sum);
;
}
}

public static int Factorial(int n) {
if (n == 0) {
return 1;
}
return n * Factorial(n - 1);
}
}
--------------------编程问答-------------------- 楼上的代码是可以实现,但还是有点不合理的地方,你声明了静态变量,就不在new了吧。你new出来的ff你也没有用啊!public class Test {
    public static void main(String[] args) {
        Test ff = new Test();
        for (int i = 0; i < 5; i++) {
            int sum = ff.Factorial(2 * (i + 1));
            System.out.println(sum);
            ;
        }
    }

     int Factorial(int n) {
        if (n == 0) {
            return 1;
        }
        return n * Factorial(n - 1);
    }
}
--------------------编程问答--------------------
引用 3 楼 hpjianhua 的回复:
可运行代码如下: 


Java code

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Test ff = new Test();
        for (int i = 0; i < 5; i++……

--------------------编程问答--------------------
引用 4 楼 pxl_1012 的回复:
楼上的代码是可以实现,但还是有点不合理的地方,你声明了静态变量,就不在new了吧。你new出来的ff你也没有用啊!public class Test {
    public static void main(String[] args) {
        Test ff = new Test();
        for (int i = 0; i < 5; i++) {
     ……


多余代码,忘记删了..哈哈 --------------------编程问答-------------------- 初学先用伪代码写下具体过程,再用代码按语法写出来就可以了 --------------------编程问答--------------------
class Test {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
int sum = Factorial(2 * (i + 1));
System.out.println(sum);
}
}

static int Factorial(int n) {
if (n == 0) {
return 1;
}
return n * Factorial(n - 1);
}
}
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,