---
title: "斐波那契数列的实现"
author: "taimukang"
date: "2012-08-17T06:31:22Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-08-17T06:31:22Z"
id: 1634688
url: "https://taimukang.iteye.com/blog/1634688"
---

//递归方式  
        public static int f(int n) {  
                //参数合法性验证  
                if (n &lt; 1) {  
                        System.out.println("参数必须大于1！" );  
                        System.exit(-1);  
                }  
                if (n == 1 || n == 2) return 1;  
                else return f(n - 1) + f(n - 2);  
        }

        //非递归方式  
        public static int fx(int n) {  
                //参数合法性验证  
                if (n &lt; 1) {  
                        System.out.println("参数必须大于1！" );  
                        System.exit(-1);  
                }  
                //n为1或2时候直接返回值  
                if (n == 1 || n == 2) return 1;

                //n&gt;2时候循环求值  
                int res = 0;  
                int a = 1;  
                int b = 1;  
                for (int i = 3; i &lt;= n; i++) {  
                        res = a + b;  
                        a = b;  
                        b = res;  
                }  
                return res;  
        }