fibonacci在python中工作但在Java中失败 [英] fibonacci works in python but fails in Java

查看:154
本文介绍了fibonacci在python中工作但在Java中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码用于在 python 中计算斐波那契数字。它起作用并给出预期的结果。但是当我将它翻译成 Java 时,它就失败了。知道这里出了什么问题吗?

I have this code for calculating fibonacci number in python. It works and gives the expected result. but when I translated the same to Java, it fails. Any idea of what is going wrong here?

python

def fib3(n): 
  a,b=0,1
  while n>0:
      a,b=b,a+b
      n-=1
  return a

fib3(12) - > 144

Java

 public static int fib2(int n){
        int a = 0;
        int b =1;
        while(n-- >0){
            a=b;
            b=a+b;

        }
    return a;
}

fib2(12) - > 2048

推荐答案

在本节中:

a=b;
b=a+b;

您将 b 分配给 a + b ,但 a 已经 b 。所以你真的加倍 b

you're assigning b to a+b, but a is already b. So really you're doubling b

最简单的解决方案是一个临时变量:

Easiest solution is a temp variable:

public static int fib2(int n){
    int a = 0;
    int b =1;
    while(n-- >0){
        int old_a;
        old_a = a;
        a=b;
        b=old_a+b;
    }
    return a;
}

在python中, a,b = b,a + b 在将新值分配给变量之前自动存储中间元组,而在Java中则需要明确它

In python, a, b = b, a + b stores an intermediate tuple automatically before assigning the new values to the variables, while in Java you need to be explicit about it

按照Python的说明, a,b = b,a + b 正在执行此反汇编:

Breaking down Python's instructions, a, b = b, a + b is executing this disassembly:

  5          17 LOAD_FAST                1 (b)
             20 LOAD_FAST                0 (a)
             23 LOAD_FAST                1 (b)
             26 BINARY_ADD
             27 ROT_TWO
             28 STORE_FAST               0 (a)
             31 STORE_FAST               1 (b)

从更简单的意义上说,保持python,这是一个过程:

In a simpler sense, staying python, here's the process:

temp_tuple = (b, a + b)
a, b = temp_tuple

这篇关于fibonacci在python中工作但在Java中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆