已知:费波那契数列的前几个数分别为 0,1,1,2,3,5……。
从第 3 项开始,每一项都等于前两项的和。读入一个整数 n,编程求出此数列的前 n 项。
注意:这里的数列是从 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]); } } }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!
Comment définir des variables dans Golang
Raisons pour lesquelles le ping échoue
Comment connecter PHP à la base de données mssql
Comment configurer le pare-feu Linux
utilisation de la fonction math.random
Comment ouvrir un fichier mdf
Introduction à la signification de javascript
Quelles sont les méthodes de tri ?