以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 Dot NET,C#,ASP,VB 』  (http://bbs.xml.org.cn/list.asp?boardid=43)
----  C#快餐-7  (http://bbs.xml.org.cn/dispbbs.asp?boardid=43&rootid=&id=11721)


--  作者:admin
--  发布时间:11/9/2004 2:25:00 AM

--  C#快餐-7


发信人: nice (春天), 信区: DotNET        
标  题: C#快餐-7
发信站: BBS 水木清华站 (Thu Jul 26 02:07:48 2001)

Lesson 7. Recursion

   Here is a simple recursive program that prints a decimal integer.


using System;
class Print
{
   public void print (int n)
   {
      if(n>=10)
      print(n/10);
      Console.Write (n%10);
   }
}

class Demo
{
   public static void Main()
   {
      Print test = new Print();
      test.print (31);
   }
}

   I have used 31 as an input, but any other number would certainly work.  
How does print work? First it checks that 31 is bigger than 10 and calls
print(3).  
   Since 3 is less than 10, 3 is printed on the console. Control  
is returned to 31, and   
   since 31%10=1 is 1, it is printed on the console.
   Since Write has no carriage return, 3 and 1 are printed side by side as 31.
   Here is a much more interesting recursive program, which generates all  
   possible permutations of  an array t;

using System;
class Perm{
   public void swap (ref int a, ref int b)
   {
      int temp = a;
      a = b;
      b = temp;
   }
   public void perm (int []list, int k, int m)
   {
      int i;
      if (k == m){
         for (i = 0; i <= m; i++)
         Console.Write (list [i]);
         Console.WriteLine (" ");
      }
      else
         for (i = k; i <= m; i++)
         {
            swap (ref list [k], ref list [i]);
            perm (list, k+1, m);
            swap (ref list [k], ref list [i]);
         }
   }
}
class Demo{
   public static void Main()
   {
      Perm test = new Perm();
      int [] t={1, 2, 3};
      test.perm(t, 0, 2);
   }
}
Output:
123
132
213
231
321
312

   Note the declaration of  integer array t : int []t  is inverse to that  
in C++.

--

※ 修改:·walts 於 Jul 26 10:07:31 修改本文·[FROM: 166.111.142.118]
※ 来源:·BBS 水木清华站 smth.org·[FROM: 166.111.176.234]
上一篇
返回上一页
回到目录
回到页首
下一篇



W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
15,343.750ms