zoukankan      html  css  js  c++  java
  • C# 求斐波那契数列的前10个数字 :1 1 2 3 5 8 13 21 34 55

    //C# 求斐波那契数列的前10个数字 :1 1 2 3 5 8 13 21 34 55

     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Text;
    
      namespace ConsoleTest
      {
       class Program
     {
    static void Main(string[] args)
    {
        OutPut4();
    }
    
    //方法1,使用while循环
    
    
    public static void OutPut1()
    {
    
        int sum = 0;  //输出的值
        int num1 = 0;
        int num0 = 0;
        int i = 0;//计数器
        while (i < 10)
        {
    
            if (i == 0)
            {
                sum = num0 = 1;
            }
            else if (i == 1)
            {
                sum = num1 = 1;
            }
            else
            {
                sum = num1 + num0;
                num0 = num1;
                num1 = sum;
            }
            Console.WriteLine(sum);
            i++;
        }
        Console.Read();
    
    }
    
    
    //方法2,使用for循环
    public static void OutPut2()
    {
        int num = 1;
        int prev = 0;
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(num.ToString());//在这里输出或者存起来
            int temp = num;
            num += prev;
            prev = temp;
        }
        Console.Read();
    }
    
    //方法3,使用数组
    public static void OutPut3()
    {
        var numArray = new int[10];
        int i = 0;
        while (i < 10)
        {
    
            if (i == 0)
            {
                numArray[i] = 1;
            }
            else if (i == 1)
            {
                numArray[i] = 1;
            }
            else
            {
                numArray[i] = numArray[i - 1] + numArray[i - 2];
            }
            Console.WriteLine(numArray[i]);
            i++;
        }
        Console.Read();
    }
    
    //方法4,使用递归循环
    public static void OutPut4()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(Calc(i));
        }
        Console.Read();
    }
    
    public static int Calc(int num)
    {
        if (num == 0 || num == 1)
        {
            return 1;
        }
        return Calc(num - 1) + Calc(num - 2);
              }
          }
      }
  • 相关阅读:
    OCP-1Z0-053-V12.02-668题
    Oracle DB 监控和优化RMAN
    OCP-1Z0-052-V8.02-123题
    OCP-1Z0-053-V12.02-151题
    OCP-1Z0-053-V12.02-66题
    OCP-1Z0-053-V12.02-163题
    OCP-1Z0-052-V8.02-51题
    OCP-1Z0-052-V8.02-53题
    ostringstream、istringstream、stringstream
    OCP-1Z0-053-V12.02-205题
  • 原文地址:https://www.cnblogs.com/renzaijianghu/p/4455572.html
Copyright © 2011-2022 走看看