简体   繁体   English

为什么使用整数而不是双精度?

[英]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. 这些格式能够表示您将要返回的值,没有理由这样做。

  • The function you're computing (a modified Fibonacci sequence) is defined over the set of integers - in fact, only positive integers. 您正在计算的函数(修改的斐波那契数列)是在整数集上定义的-实际上,只有正整数。 It will never produce a value that can not be represented by an int . 它永远不会产生不能由int表示的值。
  • double (and String ) is more expensive in both space and computation. double (和String )在空间和计算上都更加昂贵。
  • The return type is a strong indication to other developers what kind of data to expect. 返回类型是对其他开发人员的强烈指示。 Returning a 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM