llopx

能跟您分享知识,是我的荣幸

几道有趣的程序题

 1:  static class Program
 2:     {
 3:         static int x, y;
 4:   
 5:         static Program()
 6:         {
 7:             //首先执行这里,但无意义。全局变量x=0,y=0
 8:             int x = 5;
 9:         }
10:   
11:         static void Main(string[] args)
12:         {
13:             //x--后让x=-1
14:             x--;
15:             //
16:             myMethod();
17:             //执行顺序从左往右?x+y=1,x=x+1=2,1+2=3,所以最后的结果为
18:             System.Console.WriteLine(x + y + ++x);
19:             Console.Read();
20:         }
21:   
22:         public static void myMethod()
23:         {
24:             //++x先让x=x+1=0,x++让?y=0+0=0之后?x=x+1=1
25:             y = x++ + ++x;
26:         }
27:     }

 

经过代码的分析,最后的结果为3。

 

题2:以下程序会输出什么?

 

 1:  static void Main(string[] args)
 2:       {
 3:           bool a = true;
 4:           bool b = false;
 5:           bool c = true;
 6:   
 7:           if (a == true)
 8:               if (b == true)
 9:                   if (c == true)
10:                       Console.WriteLine("ss");
11:                   else
12:                       Console.WriteLine("we");
13:               else if (a && (b = c))
14:                   Console.WriteLine("wer");
15:               else
16:                   Console.WriteLine("were");
17:   
18:           Console.Read();
19:   
20:       }

 

结果为wer.

 

题3:以下程序会显示什么?

 1:  static void Main(string[] args)
 2:        {
 3:            char digit = 'a';
 4:            for (int i = 0; i < 10; i++)
 5:            {
 6:                switch (digit)
 7:                {
 8:                     case 'x' :
 9:                     {
10:                        int j = 0;
11:                         Console.WriteLine(j);
12:                     }
13:                     default :
14:                     {
15:                        int j = 100;
16:                        Console.WriteLine(j);
17:                     }
18:                }
19:   
20:            }
21:                int i = j;
22:                Console.WriteLine(i);
23:                Console.Read();
24:   
25:        }

 

会报错。

错误1:不能在此范围内声明名为“i”的局部变量,因为这样会使“i”具有不同的含义,而它已在“子级”范围中表示其他内容了。

错误2:当前上下文中不存在名称“j”。

 

Technorati 标签: c#,程序题

posted on 2010-04-26 11:17  llopx  阅读(450)  评论(0编辑  收藏  举报

导航