Known: The first few numbers of the Fibonacci sequence are 0,1,1,2,3,5….
Starting from item 3, each item is equal to the sum of the previous two items. Read in an integer n and program to find the first n items of this sequence.
Note: The sequence here starts from 0.
import java.util.Scanner;
/**
* FaibonacciNumber.java
* @author anyunpei 2018年7月22日下午3:54:11
* 计算faibonacci数列之和
*/
public class FaibonacciNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
a[0] = 0;
a[1] = 1;
System.out.println(a[0] + "\n" + a[1]);
for (int i = 2; i < n; i++) {
a[i] = a[i - 1] + a[i - 2];
if (a[i] < 0) {
System.out.println("请缩小此数列的项数,数列之和已溢出" + "最好保证在(" + i + ")项之内");
return;
}
System.out.println(a[i]);
}
}
}The above is the detailed content of Use Java to implement the sum of the first n terms of the Fibonacci sequence. For more information, please follow other related articles on the PHP Chinese website!
What are the five types of aggregate functions?
Check the occupied port status in windows
location.hash
vcruntime140.dll cannot be found and code execution cannot continue
What are the video server configuration parameters?
How to solve garbled tomcat logs
How to learn C# from scratch
How to set font color in html