日期:2010-12-27  浏览次数:20411 次

  1. 编写一个控制台应用程序,完成下列功能。

  1) 创建一个类,用无参数的构造函数输出该类的类名。

  2) 增加一个重载的构造函数,带有一个string类型的参数,在此构造函数中将传递的字符串打印出来。

  3) 在Main方法中创建属于这个类的一个对象,不传递参数。

  4) 在Main方法中创建属于这个类的另一个对象,传递一个字符串“This is a string.”。

  5) 在Main方法中声明类型为这个类的一个具有5个对象的数组,但不要实际创建分配到数组里的对象。

  6) 写出运行程序应该输出的结果。

  【解答】

  using System;
  class Test1
  {
  public Test1()
  {
  Console.WriteLine(this);
  }
  public Test1(string str)
  {
  Console.WriteLine(str);
  }
  public static void Main()
  {
  Test1 t1 = new Test1();
  Test1 t2 = new Test1("This is a string.");
  Test1[] t3 = new Test1[5];
  }
  }

  输出结果:

  Test1

  This is a string.

  2. 编写一个控制台应用程序,定义一个类MyClass,类中包含有public、private以及protected数据成员及方法。然后定义一个从MyClass类继承的类MyMain,将Main方法放在MyMain中,在Main方法中创建MyClass类的一个对象,并分别访问类中的数据成员及方法。要求注明在试图访问所有类成员时哪些语句会产生编译错误。

  【解答】

  using System;
  class MyClass
  {
  public int i;
  private int j;
  protected int k;
  public void method1()
  {
  Console.WriteLine("public method.");
  }
  private void method2()
  {
  Console.WriteLine("private method.");
  }
  protected void method3()
  {
  Console.WriteLine("protected method.");
  }
  }
  class MyMain : MyClass
  {
  public static void Main()
  {
  MyClass t = new MyClass();
  Console.WriteLine("i={0}", t.i);
  Console.WriteLine("j={0}", t.j); //会出现编译错误,私有成员不允许在其它类中访问
  Console.WriteLine("k={0}", t.k); //会出现编译错误,应该创建MyMain的对象,然
  //后通过MyMain的对象访问
  t.method1();
  t.method2(); //会出现编译错误,私有的方法不允许在其它类中调用
  t.method3(); //会出现编译错误,应该创建MyMain的对象,然后通过MyMain的
  //对象调用该方法
  }
  }

  3. 创建一个类包含有protected数据。在相同的文件里创建第二个类,用一个方法操纵第一个类里的protected数据。

  【解答】

  using System;
  class Class1
  {
  protected int i = 5;
  protected void MyMethod()
  {
  Console.WriteLine("protected method.");
  }
  }
  class Class2 : Class1
  {
  private void NewMethod()
  {
  Console.WriteLine(this.i);
  this.i += 10;
  Console.WriteLine(this.i);
  }
  public static void Main()
  {
  Class2 t = new Class2();
  t.NewMethod();
  }
  }

  4. 分别写出下列语句执行的结果。

  1) Console.WriteLine("{0}--{0:p}good",12.34F);

  2) Console.WriteLine("{0}--{0:####}good",0);

  3) Console.WriteLine("{0}--{0:00000}good",456);

  【解答】

  12.34--1,234.00%good

  0--good

  456--00456good

  5. 编写一个控制台应用程序,计算

  要求精度为10-8。

  【解答】

  using System;
  class Test5
  {
  public static void Main()
  {
  int n = 50;
  double x = 3;
  double s = 0;
  double a = 1;
  for (int i = 1; i <= n; i++)
  {
  a *= i;
  s += Math.Pow(-1, i + 1) * Math.Pow(x, i) / a;
  }
  Console.WriteLine("n={0},s={1:0.00000000}", n, s);
  }
  }

  6. 编写一个控制台应用程序,接收一个长度大于3的字符串,完成下列功能

  1) 输出字符串的长度。

  2) 输出字符串中第一个出现字母a的位置。