您的位置:首页 > 编程语言 > Java开发

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

2018-01-02 18:36 302 查看

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 --
b5c3
得到-->[5,10]

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

公式:*(最大值-最小值+1)+最小值


代码举例:求20个10之300内的最大随机数

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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息