C#中的遍歷、迭代、遞歸


算法的定義

有限的指令的序列

  • 有窮性
  • 確定性
  • 可行性

遍歷

遍歷求水仙花數:“水仙花數”是指一種三位數,它的各位數字的立方和等於該數字本身。

        public static void Main()
        {
            for(int i = 100;i < 1000;i++)
            {
                int tmpi = i;
                int a = tmpi % 10;
                tmpi /= 10;
                int b = tmpi % 10;
                tmpi /= 10;
                int c = tmpi;
                //Console.WriteLine(a + " " + b + " " + c);
                if (i == a * a * a + b * b * b + c * c * c)
                    Console.WriteLine(i);
            }


        }

直接枚舉個數、十位、百位更能體現遍歷。

迭代

        public static void Main()
        {
            int cnt = 0;  // 迭代次數
            double x1 = 2, x2 = 0;
            while(true)
            {
                x2 = x1 - (x1 * x1 * x1 - x1 - 1) / (3 * x1 * x1 - 1);  // 迭代公式
                if (Math.Abs(x2 - x1) > 0.000001)
                {
                    x1 = x2;
                    cnt++;
                }
                else break;
            }
            Console.WriteLine("方程的根:" + x1);
            Console.WriteLine("迭代次數:" + cnt);
        }
    }

遞歸

遞歸求階乘

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM