【问题标题】:Fibonacci's Sequence using forloop使用 for 循环的斐波那契数列
【发布时间】:2020-09-08 07:33:50
【问题描述】:

我正在尝试创建一个长度为 n(用户输入)的数组,我认为我可以使用数组中关联的 i 值来计算我的斐波那契和。

这是我到目前为止所拥有的,我不知道应该如何将 i 值提取为 int 以便能够计算总和。

public class Fibonacci {
    public static void main(String[] args){
        System.out.println("Please enter a value for n: ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
    
        int[] newArray = new int[n];
    
        int f1 = newArray[0];
        int f2 = newArray[1];
        
        int i;
        for(i = 1; i <= n; ++i) {
            System.out.print(f1 + " ");
            int sum = f1 + f2;
            f1 = f2;
            f2 = sum;
        }
    }
}

如果有人对如何解决这个问题有任何建议,并能解释一些理论,将不胜感激。

【问题讨论】:

  • 斐波那契数列必须从某个非零值开始。否则你只是在加零。
  • 请考虑您的要求。您希望我们为您写下一些东西……之前已经写了很多次。有很多网站详细讨论了斐波那契数列……对于初学者,也适用于专家。其中许多站点都带有各种语言的完整实现。所以:你为什么认为有必要在这里写...关于 Fib 的无数个问题,再次为您解释事情?我的观点是:您通过编程和搜索文档来学习编程。整天。向其他人寻求解释...
  • 应该是您的最后选择。然后它应该是一个具体的问题,而不是像“这是我的代码,现在是什么”。
  • 请注意:放弃您的问题,然后走开,仅在数小时或数天后返回也不受欢迎。

标签: java for-loop fibonacci


【解决方案1】:

如果您使用数组来存储斐波那契数列,则应使用该数组中的索引访问斐波那契数,无需使用中间变量f1, f2, sum

int[] fiboNums = new int[n]; // assuming n >= 2
    
fiboNums[0] = 1;
fiboNums[1] = 1;

System.out.printf("f(%2d)=%,13d  ", i, fiboNums[i]);        
for (int i = 2; i < n; i++) {
    fiboNums[i] = fiboNums[i - 1] + fiboNums[i - 2];

    System.out.printf("f(%2d)=%,13d  ", i, fiboNums[i]);
    if (i % 5 == 0) {
        System.out.println();
    }
}

但是,使用int 表示斐波那契数可能不是一个好主意,因为这个数列呈指数增长,当i == 46 时会发生整数溢出。

f( 1)=            1  f( 2)=            2  f( 3)=            3  f( 4)=            5  f( 5)=            8  
f( 6)=           13  f( 7)=           21  f( 8)=           34  f( 9)=           55  f(10)=           89  
f(11)=          144  f(12)=          233  f(13)=          377  f(14)=          610  f(15)=          987  
f(16)=        1,597  f(17)=        2,584  f(18)=        4,181  f(19)=        6,765  f(20)=       10,946  
f(21)=       17,711  f(22)=       28,657  f(23)=       46,368  f(24)=       75,025  f(25)=      121,393  
f(26)=      196,418  f(27)=      317,811  f(28)=      514,229  f(29)=      832,040  f(30)=    1,346,269  
f(31)=    2,178,309  f(32)=    3,524,578  f(33)=    5,702,887  f(34)=    9,227,465  f(35)=   14,930,352  
f(36)=   24,157,817  f(37)=   39,088,169  f(38)=   63,245,986  f(39)=  102,334,155  f(40)=  165,580,141  
f(41)=  267,914,296  f(42)=  433,494,437  f(43)=  701,408,733  f(44)=1,134,903,170  f(45)=1,836,311,903

同样,使用long 将只允许拟合 91 个斐波那契数。

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2023-03-12
    • 2023-03-23
    相关资源
    最近更新 更多