函数是什么?
是一块代码,接受零个或是多个参数,做一件事,并返回零个或一个值
函数定义
public static void sum(int a ,int b)//函数头
{
int i; /
int sum;
sum = 0;
for(i = a;i<=b;i++)
{
sum +=i;
}
System.out.println(a+"到"+b+"的和是"+sum);/函数体
}
调用函数
函数名(参数值)
()起到了表示函数调用的重要性
即使没有参数也需要()
public static void f()
{
System.out.println("f()");
}
如果有参数,则需要给出正确的数量和顺序
这些值会被按照顺序依次用来初始化函数中的参数
public static void main(String[] args) {
// TODO 自动生成的方法存根
f();
sum(1,10);
sum(20,30);
sum(35,45);
}
函数返回值
return:停止函数的执行,并且返回一个值
1. return;
2. return 表达式;
public static int max(int a ,int b )
{
int ret;
if(a>b)
{
ret=a;
}
else
{
ret=b;
}
return ret;
}
函数调用
如果函数有参数,调用函数时必须传递给它数量、类型正确的值
可以传递给函数的值是表达式的结果,包括:
字面值
变量
函数返回值
计算的结果
public static void main(String[] args) {
// TODO 自动生成的方法存根
f();
sum(1,10);
sum(20,30);
sum(35,45);
int a = 5;
int b = 6;
int c;
c = max(10,12);
c = max(a,b);
c = max(a,23);
c = max(c,23);
c = max(max(c,a),max(5,b));
}
类型不匹配
当函数期望的参数类型比调用函数时给的值的类型宽的时候,编译器能悄悄替你把类型转换好
char-->int-->double
public static int max(double a ,int b )//参数
{
int ret;
if(a>b)
{
ret=(int)a;
}
}
public static void main(String[] args) {
int a = 5;
int b = 6;
int c;
c
=
max
(10,12);
c = max(a,b);
}
传值
每个函数每一次运行有自己的变量空间,参数也位于这个独立的空间中,和其他函数没有关系
public
static
int
max(
double
a
,
int
b
)//参数
c = max(10,12);
c = max(a,b);//值
变量的生存期和作用域
生存期:什么时候这个变量开始出现。到什么时候消亡
作用域:在(代码的)什么范围内可以访问这个变量
大括号内