如何以菱形图案打印斐波那契数字

时间:2016-11-16 08:25:06

标签: java

根据用户输入(行数)以菱形图案打印斐波纳契系列。 用户将输入行数,输出应包含打印Fibonacci系列的许多行

import java.util.*;

public class HelloWorld {
    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);

        //Taking noOfRows value from the user
        System.out.println("Enter no of rows:");
        int noOfRows = sc.nextInt();

        //Initializing rowCount with 1
        int rowCount = 1;

        //Implementing the logic
        int previous = 0, prevtoprev;
        for (int i = noOfRows; i > 0; i--) {

            //Printing i*2 spaces at the beginning of each row
            for (int j = 1; j <= i*2; j++) {
                System.out.print(" ");
            }

            //Printing j value where j value will be from 1 to rowCount
            for (int j = 1; j <= rowCount; j++) {
                if (j%2 == 0) {
                    System.out.print("+");
                } else {
                    System.out.print(j);
                }
            }

            //Printing j value where j value will be from rowCount-1 to 1
            for (int j = rowCount-1; j >= 1; j--) {
                if (j%2 == 0) {
                    System.out.print("+");
                } else {
                    System.out.print(rowCount);
                }
            }

            System.out.println();

            //Incrementing the rowCount
            previous = rowCount;
            rowCount++;
        }
    }
}

输出

enter image description here

预期产出:

这里“34”分裂为“4”进入下一行形成一个钻石,“144”分裂为在最后一行放置“1”,剩下的数字'44'被丢弃。

enter image description here

2 个答案:

答案 0 :(得分:2)

以下是一些代码。尝试理解它并在必要时进行修改。仅当行号为奇数且行号不大于23时才有效。 尝试自己改进它。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class NewClass {

    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows:");
        int noOfRows = sc.nextInt();
        while(noOfRows%2==0){
           System.out.println("Only an odd number can be inserted. Enter number of rows:");
           noOfRows = sc.nextInt(); 
        }
        String str = concatFibSeries(noOfRows*3);
        List<String> list = chopp(str,noOfRows);
        printDimondPattern(list);
    }
    // Formula for the n-th Fibonacci number
    static int nthFib(int n){
        return (int)( ( 1/Math.sqrt(5) )* ( (Math.pow( ( ( 1+Math.sqrt(5) )/2),n ) ) - (Math.pow( ( ( 1-Math.sqrt(5) )/2),n ) ) ) );    
    }
    // returns a string of all Fibonacci numbers upto the nth Fibonacci number concatenated with "+"
    static String concatFibSeries(int n){
        StringBuilder sb = new StringBuilder();
        for(int i= 1; i<=n; i++){
            sb.append(nthFib(i)).append("+");
        }
        return sb.toString();
    }
    // cuts the string returned by the method concatFibSeries(int n) into small chunks
    // returns a list of strings with list.size equal to given rows
    // the length of the strings beginns by one and increases by two on each step till the middle row is reached
    // and decreases by two till the end of rows is reached
    static List<String> chopp(String concatenatedString,int rows){
        List<String> list = new ArrayList<>();
        for(int i = 1, j = 1; i <= rows; i++, j=(i<= Math.ceil(rows/2.))? j+2 : j-2){
           list.add(concatenatedString.substring(0,j));
           concatenatedString = concatenatedString.substring(j);
           if (concatenatedString.startsWith("+")){
               concatenatedString = concatenatedString.substring(1);
           }
        }
        return list;    
    }
    // adds the required space before and after each string and prints the string
    static void printDimondPattern(List<String> list){
        for(int i = 0; i< list.size();i++){
            String str ="";
            for (int j = 0; j<(Math.abs(list.size()-Math.ceil(list.size()/2.)-i));j++){
                str +=" ";
            }
            System.out.println(str+list.get(i)+str);
        }
    }        
}

答案 1 :(得分:0)

我可以根据行数打印斐波纳契系列 但仍然不是正确的,我需要用&#34; +&#34;来安排钻石图案。如果它不合适,也会丢弃额外的数字。

    import java.util.*;
    public class HelloWorld{

     public static void main(String []args){
         meth();
     }
     public static int meth(){
         int row, column, first_no = 1, second_no = 1, sum = 1;

        Scanner sc = new Scanner(System.in);
        //Taking noOfRows value from the user
        System.out.println("Enter no of rows:");
        row = sc.nextInt();

        for (int i = 1; i <= row; i++) {
            for (column = 1; column <= i; column++) {
                if (i == 1 && column == 1) {
                System.out.printf("%"+(row)+"d\t",second_no);
                continue;
         }
         System.out.printf(" %d ", sum);

         //Computes the series
         sum = first_no + second_no;
         first_no = second_no;
         second_no = sum;
      }
      System.out.println("");
   }
   return 0;
}
}

输入:4

输出为:

enter image description here