[英]Why use an integer versus a double?
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
. 我想知道为什么返回类型是
int
。 What does it afford you? 它给你带来什么? Why can't the return type be
double
? 为什么返回类型不能为
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
. 当然,您可以定义函数以返回
double
,也可以将其定义为返回String
。 The formats are capable of representing the values you'll be returning, there's just no reason to do it. 这些格式能够表示您将要返回的值,没有理由这样做。
int
. int
表示的值。 double
(and String
) is more expensive in both space and computation. double
(和String
)在空间和计算上都更加昂贵。 double
that will only contain 1, 2, 3, ...
is to some extent misleading. 1, 2, 3, ...
的double
精度在某种程度上具有误导性。 So use double
if you like; 因此,如果愿意,请使用
double
; it will work just fine. 它会很好地工作。 But the question is more "why?"
但问题更多是“为什么?” than "why not?".
比“为什么不呢?”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.