JAVA基础之函数 随机数函数介绍

JAVA基础

函数

定义
封装了具有特定功能的代码块;
函数的写法
关键字 返回值类型 函数名(参数类型 参数1,参数类型 参数2,....){
       函数中的语句1;
       语句2;
       return 返回值 //return 后面返回的 返回值 要跟函数的返回值类型 对应
}
函数的书写位置
在定义好的类中书写
函数的分类
1.无参数 无返回值 的 函数
2.无参数 有返回值 的 函数
3.有参数 有返回值 的 函数
4.有参数 误返回值 的 函数
函数的特点
函数中不可以定义函数
函数可以重名
函数的调用
使用 函数名(传入的参数);
编写函数的步骤
1.确定函数有没有返回值(接下来 是否要使用这个返回值 根据实际情况考虑)
2.确定函数有没有参数 有的话 是几个 都什么类型

函数的重载

定义
实现相同的功能 但是函数的内部实现不同
特点
1.函数的重载 是 函数名字相同 并且只跟参数有关
(参数的类型 参数的顺序 参数的个数)
跟参数的返回值无关
2.java里没有函数的声明,可以直接使用函数
用处
需要站在函数使用者的角度上取考虑问题 使用时更方便
举例
public static void fun(int a, double b, char c);

public static void fun(int z, double w, char z);  //不是重载

public static void fun(int a, char c ,double b);  //重载

public static void fun(int a, double b);  //重载
代码练习

    public static void main(String[] args) {
		System.out.println(fun(1,5,9,4,3));
	}
    
    public static int fun(int a, int b) {
    	int max = (a > b) ? a : b;
    	
    	return max;
    }
    
    public static int fun(int a, int b,int c) {
    	int m = fun(a, b);
    	int max = (m > c) ? m : c;
    	
    	return max;
    }
    
    public static int fun(int a, int b, int c, int d) {
    	int m = fun(a, b, c);
    	int max = (m > d ) ? m : d;
    	
    	return max;
    }
    
    public static int fun(int a, int b, int c, int d, int e) {
    	int m = fun(a, b, c, d);
    	int max = (m > e ) ? m : e;
   
    	return max;
    }

random函数

简介:
调用这个Math.random()函数能够返回带正号的double值,该值大于等于0.0且小于1
即取值范围是[0.0,1.0)的左闭右开区间,返回值是一个伪随机数,在该范围内(近似)
均匀分布
举例
初始值[0,1)
*6 --得到-->[0,6)--取整-->[0,5]
+5 --得到-->[5,10]


[18,200]
[0,1]
*183--得到-->[0,183)--取整-->[0,182]
+18--得到-->[18,200]

公式:*(最大值-最小值+1)+最小值
代码举例:求20个10之300内的最大随机数
当用int类型进行强制转换时,会自动丢弃小数位,不会进行四舍五入算法
如果想进行四舍五入可以用Math.round(doubel d)
向上取整Math.ceil(double d)
向下取整Math.floor(double d)


public static void main(String[] args){
    int max = 0;
    for(int i = 0;i < 20;i++){
        int num = (int)(Math.random()*(300 - 10 + 1))+10;
        if(max < num){
            max = num;
        }
    }
    System.out.println(max);
}

函数的递归

定义
调用一个和自己函数名相同的函数(自己调自己玩)
代码举例
public static void main(String[] args) {
	//fun(4);
	int total = func(4);
	System.out.println(total );
}
public static void fun(int num) {
	int total = 1;
	for (int i = 1; i <= num; i++) {
		total = total * i;
	}
	System.out.println(total);
}
	
public static int func(int num) {
	//递归出口(停止递归)
	//没有出口,相当于 死循环
	if(num == 1) {
			return 1;
	}else {
		return num * func(num - 1);
	}
		
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值