Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- //Aluno: Lucas David Canellas
- //Matricula: 218.083.120
- //Calcule a série de Fibonacci para um número inteiro não negativo informado pelo usuário.
- //A série de Fibonacci inicia com os números F 0 = 0 e F 1 = 1, e cada número posterior
- //equivale à soma dos dois números anteriores (F n = F n-1 + F n-2 ). Por exemplo, caso o usuário
- //informe o número 9, o resultado seria: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
- public class Fibonacci {
- public static void main(String[] args) {
- int f0 = 0;
- int f1 = 1;
- int aux = 0;
- int numero = 0;
- Scanner teclado = new Scanner(System.in);
- System.out.println("#### FIBONACCI###");
- System.out.println("Insira o numero: ");
- numero = teclado.nextInt();
- if (numero < 0) { // caso a entrada seja negativa, o programa termina
- System.out.println("Apenas sao aceitos numeros inteiros nao negativos");
- } else if (numero == 0) {
- System.out.println(f0);
- } else if (numero == 1) {
- System.out.printf("%d, %d", f0, f1);
- } else {
- System.out.printf("%d, %d", f0, f1);// imprime os elementos 0 e 1 da sequencia
- for (int i = 1; i < numero; i++) {
- aux = f0;// guardo o valor de f0 em uma variavel auxloiar para usar posteriormente
- f0 = f1;
- f1 = f1 + aux;
- System.out.printf(", %d", f1);// imprime o restante dos elementos;
- }
- }
- teclado.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement