A1 = 1 ; A2 = 100;An+2 = |An+1 - An| 重复的从键盘录入一个正整数N(N <= 300) 计算出AN并输出,直到输出的N<=0
代码应该怎么写

解决方案 »

  1.   

    用递归
    long f(n){
       if(n==1) return 1;
       if(n==2) return 100;
       return f(n-1)-f(n-2);
    }
      

  2.   

    那个经典的什么数列问题嘛。
    嗯while死循环+Scanner.nextLine()+递归函数计算
    见楼上。
      

  3.   

    public class ShiTi4{
        public static long A(int N){
            if(N == 1){
                return 1;
            }else if(N == 2){
                return 100;
            }else{
                return A(N - 1) - A(N - 2);
            }
        }
        public static void main(String[] args){
            Scanner scan = new Scanner(System.in);
            while(true){
                System.out.println("重复的从键盘读入一个正整数N(<=300)");
                String N = scan.nextLine().trim();
                if(!N.matches("^[\\+\\-]?\\d+$")){
                    continue;
                }else if(N > 0){
                    System.out.println(A(N));
                }else{
                    scan.close();
                    break;
                }
            }
        }
    }哪里出错了,运行不了
      

  4.   


    public class ShiTi4{
        public static long A(int N){
            if(N == 1){
                return 1;
            }else if(N == 2){
                return 100;
            }else{
                return A(N - 1) - A(N - 2);
            }
        }
        public static void main(String[] args){
            Scanner scan = new Scanner(System.in);
            while(true){
                System.out.println("重复的从键盘读入一个正整数N(<=300)");
                String N = scan.nextLine().trim();
                if(!N.matches("^[\\+\\-]?\\d+$")){
                    continue;
                }else if(N > 0){
                    System.out.println(A(N));
                }else{
                    scan.close();
                    break;
                }
            }
        }
    }
    哪里出错了运行不了
      

  5.   


    public class ShiTi4{
        public static long A(int N){
            if(N == 1){
                return 1;
            }else if(N == 2){
                return 100;
            }else{
                return A(N - 1) - A(N - 2);
            }
        }
        public static void main(String[] args){
            Scanner scan = new Scanner(System.in);
            while(true){
                System.out.println("重复的从键盘读入一个正整数N(<=300)");
                String N = scan.nextLine().trim();
                if(!N.matches("^[\\+\\-]?\\d+$")){
                    continue;
                }else if(N > 0){
                    System.out.println(A(N));
                }else{
                    scan.close();
                    break;
                }
            }
        }
    }
    哪里出错了运行不了
    int N=scan.nextInt();
      

  6.   

    你的N>0这里,N还是字符串呢,怎么和整数比较?