[VB6][VB.NET][C#][JAVA] 遞迴函數

摘要:[VB6][VB.NET][C#][JAVA] 遞迴函數

遞迴(Recursive)
遞迴的優點:
1.增加程式的可讀性
2.可處理較複雜的問題

遞迴的缺點:
1.需花費較多的時間
2.利用暫存堆疊(Stack)的觀念,需要額外的儲存空間,效能比較差

VB6&VBA:

Option Explicit
Private Sub Command1_Click()
    If IsNumeric(Text1.Text) Then Text2.Text = f1(CInt(Text1.Text))
    If IsNumeric(Text1.Text) Then Text3.Text = f2(CInt(Text1.Text))
End Sub

'計算1乘到N的函數:
Private Function f1(ByVal n As Integer) As Double
    Select Case n
    Case 1
        f1 = 1
    Case Else
        f1 = n * f1(n - 1)
    End Select
End Function

'計算1加到N的函數:
Private Function f2(ByVal n As Integer) As Double
    Select Case n
    Case 1
        f2 = 1
    Case Else
        f2 = n + f2(n - 1)
    End Select
End Function

VB.NET 2005:

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If IsNumeric(TextBox1.Text) Then TextBox2.Text = f1(CInt(TextBox1.Text))
        If IsNumeric(TextBox1.Text) Then TextBOX3.Text = f2(CInt(TextBox1.Text))
    End Sub

    '計算1乘到N的函數:
    Private Function f1(ByVal n As Integer) As Double
        Select Case n
            Case 1
                f1 = 1
            Case Else
                f1 = n * f1(n - 1)
        End Select
    End Function

    '計算1加到N的函數:
    Private Function f2(ByVal n As Integer) As Double
        Select Case n
            Case 1
                f2 = 1
            Case Else
                f2 = n + f2(n - 1)
        End Select
    End Function

End Class

JAVA:

private static double rfc(int g)
{
   switch (g)
   {
   case 1:
       return 1;
       //break;
   default:
      return  g * rfc(g - 1);
   }

}

C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            int n;
            if (int.TryParse(textBox1.Text, out n))
            {
                //為數字
                int va = Int32.Parse(textBox1.Text);
                textBox2.Text = System.Convert.ToString(rfc(va));
            }

            else
            {
                MessageBox.Show ("請輸入數字");
            }

            
            
        }

        private static double rfc(int g)
        {
            switch (g)
            {
                case 1:
                    return 1;
                default:
                    return g * rfc(g - 1);
            }

        }

    }

}

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo