簡體   English   中英

在用戶輸入處停止的數字

[英]Numbers to stop at the user's input

如何讓我的程序在用戶輸入時停止? 這是我的代碼:

public class H {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Input x: ");
        int x = input.nextInt();

        for (int i = 0; i < x; i++) {
            if (i < x)
                System.out.print(printFib(i) + " ");
            else if (i > x)
                break;
        }
    }

    public static int printFib(int number) {
        if (number == 0 || number == 1)
            return number;
        else
            return printFib(number - 1) + printFib(number - 2);
    }
}

所以,如果我輸入 10,我的程序應該在數字之前停止。 例子:

輸入:10

輸出:0 1 1 2 3 5 8

但是我得到 0 1 1 2 3 5 8 13 21 34

我該如何解決?

    int x = input.nextInt();
    int fib = 0;    
        while (fib < x){


    System.out.print(printFib(fib)+ " ");
       fib++;


    }
}

不要使用現在用於打印斐波那契數字的for循環,直到打印的項目數小於輸入的數字。 而是使用while循環,當斐波那契數本身大於輸入的數字時停止。

由於這可能是家庭作業,我只是要給出這個建議而不是代碼解決方案,但請嘗試一個解決方案,如果仍然卡住,請回來提出問題。

偽代碼

Get value of x
create fibonacci variable and assign it 0
while fibonacci is less than x
   display current fibonacci number
   calculate next fibonacci number and place in variable
end while loop
public class H {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Input x: ");
    int x = input.nextInt();

    int i = 0;
    while ( printFib(i) <= x ) {
        System.out.print(printFib(i) + " "); 
        i ++ ;
    }
}

public static int printFib(int number) {
    if (number == 0 || number == 1)
        return number;
    else
        return printFib(number - 1) + printFib(number - 2);
}

}

雖然從printFib()方法返回的數字小於等於用戶輸入,但它會運行該方法。 我已經嘗試過代碼並且它有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM