Advertisement
lucas-canellas

exercicios-lista1-08

Jan 18th, 2020
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. //Aluno: Lucas David Canellas
  4. //Matricula: 218.083.120
  5.  
  6. //Calcule a série de Fibonacci para um número inteiro não negativo informado pelo usuário.
  7. //A série de Fibonacci inicia com os números F 0 = 0 e F 1 = 1, e cada número posterior
  8. //equivale à soma dos dois números anteriores (F n = F n-1 + F n-2 ). Por exemplo, caso o usuário
  9. //informe o número 9, o resultado seria: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
  10.  
  11. public class Fibonacci {
  12.  
  13.     public static void main(String[] args) {
  14.  
  15.         int f0 = 0;
  16.         int f1 = 1;
  17.         int aux = 0;
  18.         int numero = 0;
  19.  
  20.         Scanner teclado = new Scanner(System.in);
  21.  
  22.         System.out.println("#### FIBONACCI###");
  23.         System.out.println("Insira o numero: ");
  24.         numero = teclado.nextInt();
  25.  
  26.         if (numero < 0) { // caso a entrada seja negativa, o programa termina
  27.             System.out.println("Apenas sao aceitos numeros inteiros nao negativos");
  28.         } else if (numero == 0) {
  29.             System.out.println(f0);
  30.         } else if (numero == 1) {
  31.             System.out.printf("%d, %d", f0, f1);
  32.         } else {
  33.             System.out.printf("%d, %d", f0, f1);// imprime os elementos 0 e 1 da sequencia
  34.             for (int i = 1; i < numero; i++) {
  35.                 aux = f0;// guardo o valor de f0 em uma variavel auxloiar para usar posteriormente
  36.                 f0 = f1;
  37.                 f1 = f1 + aux;
  38.                 System.out.printf(", %d", f1);// imprime o restante dos elementos;
  39.             }
  40.         }
  41.  
  42.         teclado.close();
  43.  
  44.     }
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement