zoukankan      html  css  js  c++  java
  • Java日志第51天 2020.8.27

    4.10 5个人坐在一起,问第5个人多少岁?他说比第4个人大两岁。问第4个人岁数,他说比第3个人大两岁。问第3个人,又说比第2个人大两岁。问第2个人,说比第1个人大两岁。最后问第1个人,他说是10岁。请问第5个人多大?

     

    public class Demo4_10 {
        public static void main(String[] args) {
            System.out.println(age(5));
        }

        private static int age(int n){
            int c;
            if(n == 1)
                c = 10;
            else
                c = age(n-1)+2;
            return c;
        }
    }

     

    4.11 用递归方法求n!

    import java.util.Scanner;

    public class Demo4_11 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n;
            long y;

            System.out.print("Please input an integer:");
            n = sc.nextInt();
            y = fac(n);
            System.out.println(n+"! = "+y);
        }

        private static long fac(int n) {
            long f;
            if(n<0) {
                System.out.println("n<0, data error!");
                f = -1;
            } else if (n==0 || n==1){
                f = 1;
            } else
                f = fac(n-1)*n;
            return f;
        }
    }

     

     

    4.12 静态局部变量的值

    public class Demo4_12 {
        static int c = 3;
        public static void main(String[] args) {
                int a = 2;
            for (int i = 0; i < 3; i++) {
                System.out.println(f(a));
            }
        }

        private static int f(int a) {
            int b = 0;
            b = b+1;
            c = c+1;
            return a+b+c;
        }
    }

     

     

     

    4.13 输出1~5的阶乘值(即1!, 2!, 3!, 4!, 5!)

    public class Demo4_13 {
        static int f = 1;
        public static void main(String[] args) {
            for (int i = 1; i <= 5; i++) {
                System.out.println(i+"! = "+fac(i));
            }
        }

        private static int fac(int n){
            f = f*n;
            return f;
        }
    }

     

     

    4.14 extern对外部变量作提前引用声明,以扩展程序文件中的作用域。

    4.15 输入两个整数,要求输出其中的大者。用外部函数实现。

    4.16 在调试程序时,常常希望输出一些所需的信息,而在调试完成后不再输出这些信息。可以在源程序中插入条件编译段。下面是一个简单的示例。

  • 相关阅读:
    谷歌Cartographer ROS初探
    在Ubuntu14.04_ROS_indigo上安装Kinect2驱动和bridge
    Turtlebot入门篇
    关于CV、SLAM、机器人导航的碎碎念
    C#与C++的区别!
    ++i 与 i++
    "+" 是怎样连接字符串的?
    不要重复你自己
    实习第四天
    微信小程序添加外部地图服务数据
  • 原文地址:https://www.cnblogs.com/Gazikel/p/13574473.html
Copyright © 2011-2022 走看看