2016-11-16 2 views
-2

다이아몬드 패턴으로 fibonacci 계열을 인쇄 할 사용자 입력 (행 수)을 기반으로합니다. 사용자는 행의 번호를 입력하고 출력은다이아몬드 패턴에서 fibonacci 숫자를 인쇄하는 방법

enter image description here

예상 출력으로 피보나치 시리즈

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++; 
     } 
    } 
} 

을 얻기 출력을 인쇄하는 많은 행을 포함해야한다 : 여기

"(34) "는 다이아몬드를 형성하기 위해 다음 행에"4 "를 배치하고 마지막 행에"1 "을 배치하기 위해"144 "가 분할되고 나머지 자릿수 '44'는 버려집니다. 내가 행 의 수를 기준으로 피보나치 시리즈를 인쇄 할 수 있어요 그러나 여전히 올바른 일이 아니다

enter image description here

+0

부정적 점검을하는 사람들이 거의없는 이유는 무엇입니까? – Girish

+0

예상되는 출력은 무엇입니까? –

+1

질문을 편집하십시오. 코드를 선택하고'{} '버튼을 클릭하여 코드를 올바르게 포맷하십시오. "다이아몬드 형식"이 무엇이고 예상되는 결과가 무엇인지 설명하고 * 질문하십시오 *. – RealSkeptic

답변

0

, 나는 "+"기호 다이아몬드 패턴으로 배열하고 또한 추가 숫자의 경우를 폐기해야 그것은 적합하지 않습니다.

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

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); 
     } 
    }   
} 
관련 문제