I have code for two versions of the same function: one iterative and one recursive. I want to know why the return type is int
. What does it afford you? Why can't the return type be double
?
public static int iterative(int n){
int var=1;
int var1=1;
int var2=1;
if (n<=1) {
return 1;
}
for(int i=2;i<=n;i++){
var=var1+var2+1;
var2=var1;
var1=var;
}
return var;
}
private static int recursive(int n){
if (n<=1){
return 1;
}
return rec(n-1)+rec(n-2)+1;
}
public static void main(String[] args) {
System.out.println(iter(10));
}
You could certainly define the function to return a double
, in the same way you could define it to return a String
. The formats are capable of representing the values you'll be returning, there's just no reason to do it.
int
. double
(and String
) is more expensive in both space and computation. double
that will only contain 1, 2, 3, ...
is to some extent misleading. So use double
if you like; it will work just fine. But the question is more "why?" than "why not?".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.