1.函数基础
Code-1:函数调用
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int res = fact(5);
System.out.println(res);
}
public static int fact(int val){
int res = 1;
for(int i=1;i<=val;i++){
res = res * i;
}
return res;
}
}
Code-2:八大基本类型或String参数传递值不改变
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int val = 10;
fact(val);
System.out.println(val); //val = 10
}
public static void fact(int val){
val = 5;
}
}
Code-3:引用传递值会改,除了String与基本类型的其他类型,比如数组,StringBuilder等
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder(" ");
fact(sb);
System.out.println(sb); // Hello World
}
public static void fact(StringBuilder str){
str.append("Hello World");
}
}
Code-4:函数重载,同一个函数名可以出现多次
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(max(3,4));
System.out.println(max(3.0,4.0));
}
public static int fact(int a,int b){
System.out.println("int");
if(a>b) return a;
return b;
}
public static double fact(double a,double b){
System.out.println("double");
if(a>b) return a;
return b;
}
}
Code-5:函数递归
class Main{
public static int fib(int n){
if(n<=2) return 1;
return fib(n-1)+fib(n-2);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(fib(sc.nextInt()));
}
}
Code-6:实现斐波那契数列
class Main{
public static int fib(int n){
if(n<=2) return 1;
return fib(n-1)+fib(n-2);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(fib(sc.nextInt()));
}
}