菜鸟关于return的问题....
wwnxs 2008-04-26 11:06:50 public class Fab {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fab(8));
}
public static long fab(int index){
if(index<1){
System.out.println("error!");
return -1;
}
if(index == 1||index == 2){
return 1;
}
long f = 0, f1 = 1l, f2 = 1l;
for(int i = 1; i<=index-2; i++){
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
}
上面这个程序,如果把return f;放在for循环里,即:
public class Fab {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fab(8));
}
public static long fab(int index){
if(index<1){
System.out.println("error!");
return -1;
}
if(index == 1||index == 2){
return 1;
}
long f = 0, f1 = 1l, f2 = 1l;
for(int i = 1; i<=index-2; i++){
f = f1 + f2;
f1 = f2;
f2 = f;
return f;
}
}
}
把return放在for循环里会报错,提示“This method must return a type of long”,为什么会提示返回值f和声明的long类型不符呢?