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类型不符呢?
* @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类型不符呢?
return f放在for{}里面的话for不是失去意义了么?
怎么会呢?在for循环前已经定义了f1,f2的值都是1L。怎么还会是int呢。
两个if判断中分别有各自的return值 但是if后的模块却没有
如果lz想把return放进for循环 在循环外要再加一个return 0;(或其他 起标识作用)
lz试试~
要保证函数的每一条path都有返回。所以如果程序逻辑能到达for循环外,那么没有返回就报错了。
而3楼说的return放for里没意义是不对的,这要看程序逻辑。