古典問題:有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每 – JAVA編程語言程序開發技術文章

</pre><p> 第一種方法:</p><pre class="java" name="code">import java.util.Scanner; 
 
public class Rab{ 
    public static void main(String[]args){ 
        int month; 
        System.out.println("請輸入養殖兔子的月份數:"); 
        Scanner in = new Scanner(System.in); 
        month = in.nextInt(); 
         
        int sum[]= new int[month] ; 
        sum[0] = 1; 
        sum[1] = 1; 
             
        for(int i=2;i<month;i++){ 
            sum[i] = sum[i-1]+sum[i-2]; 
        } 
                 
        System.out.println("第"+month+"個月的兔子總數是:"+sum[month-1]); 
         
    } 

第二種方法:
[java]
import java.util.Scanner; 
 
 
public class practies4 { 
    public static void main(String[]args){ 
    //變量聲明; 
        int n = 0;  
        while(n<3){ 
            GetKey gk = new GetKey(); 
            n = gk.getN(); 
        } 
        System.out.println("請輸入月份數:"); 
        Scanner in = new Scanner(System.in); 
        n = in.nextInt(); 
         
        int[]a = new int[n]; 
        a[0]=1; 
        a[1]=1; 
        for(int i=2;i<n;i++){ 
            a[i]=a[i-1]+a[i-2]; 
        } 
        System.out.println(n); 
        System.out.println(a[n-1]); 
    } 

 
//實現對用戶輸入內容的控制,並獲取n 
class GetKey{ 
    private int pos; 
    private String bufNum=""; 
    private byte[]buff =new byte[10]; 
    private int n; 
    private int info; 
    public int getN(){ 
        System.out.println("請輸入你想知道第多少個月的兔子總數:"); 
        System.out.println("月份數必須大於2"); 
        while(true){ 
            try{ 
                info=System.in.read(); 
            }catch(Exception e){ 
            } 
             
            if(info=='\n'||info=='\r'){ 
                bufNum = new String(buff,0,pos); 
                try{ 
                    n=Integer.parseInt(bufNum); 
                }catch(Exception e){ 
                        n=1; 
                } 
                break; 
            }else{ 
                buff[pos++]=(byte)info; 
            } 
        } 
        return n; 
    } 

 

摘自 djw10962000的專欄

發佈留言