首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 基礎程式設計練習題與解答(三):建構函式、繼承、字串格式化與陣列操作

     編輯:關於C語言

練習 1:建構函式多載與陣列宣告

撰寫一個主控台應用程式,完成下列功能:

  1. 建立一個類別,其無參數建構函式輸出該類別的名稱。
  2. 增加一個帶有 string 參數的多載建構函式,列印傳入的字串。
  3. 在 Main 方法中建立該類別的一個物件,不傳遞參數。
  4. 在 Main 方法中建立另一個物件,傳遞字串 "This is a string."。
  5. 宣告一個包含 5 個該類別元素的陣列,但不實際建立物件實例。
  6. 寫出程式執行後的輸出結果。

參考程式碼

using System;

class Test1
{
    public Test1()
    {
        Console.WriteLine(this.GetType().Name); // 輸出類別名稱
    }

    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.

解析: 陣列 t3 僅在堆疊上配置參考空間,元素預設為 null,因此不會觸發建構函式,無額外輸出。


練習 2:存取修飾詞與繼承中的成員可見性

定義類別 MyClass,包含 public、private、protected 欄位與方法。再定義繼承類別 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);           // 正常:public 欄位
        // Console.WriteLine("j={0}", t.j);       // 編譯錯誤:private 欄位不可從外部類別存取
        // Console.WriteLine("k={0}", t.k);       // 編譯錯誤:protected 欄位需透過衍生類別實例存取
        t.Method1();                              // 正常:public 方法
        // t.Method2();                           // 編譯錯誤:private 方法
        // t.Method3();                           // 編譯錯誤:protected 方法需透過衍生類別實例呼叫
    }
}

重點: private 成員僅限定義類別內部存取;protected 成員允許衍生類別透過 this 或衍生類別實例存取,但不允許透過基類別實例存取。


練習 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); // 存取繼承的 protected 欄位
        this.i += 10;
        Console.WriteLine(this.i);
    }

    public static void Main()
    {
        Class2 t = new Class2();
        t.NewMethod();
    }
}

輸出: 5 後接 15。


練習 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:p} 以百分比格式顯示,數值乘 100 並加 % 號
0--good                // {0:####} 數值為 0 時不顯示任何數字
456--00456good         // {0:00000} 以 5 位數字顯示,不足前補 0

練習 5:級數求和(精度 10⁻⁸)

計算級數 S = x - x²/2! + x³/3! - ... + (-1)^(n+1) * x^n / n!,其中 n=50, x=3,要求精度達 10⁻⁸。

參考程式碼

using System;

class Test5
{
    public static void Main()
    {
        int n = 50;
        double x = 3;
        double sum = 0;
        double factorial = 1;

        for (int i = 1; i <= n; i++)
        {
            factorial *= i; // 累乘得到 i!
            // (-1)^(i+1) * x^i / i!
            sum += Math.Pow(-1, i + 1) * Math.Pow(x, i) / factorial;
        }

        Console.WriteLine("n={0}, s={1:0.00000000}", n, sum);
    }
}

練習 6:字串綜合操作

撰寫主控台程式,接收長度大於 3 的字串,完成:

  1. 輸出字串長度。
  2. 輸出第一個字母 'a' 的位置(索引)。
  3. 在第 3 個字元後插入 "hello" 並輸出。
  4. 將 "hello" 替換為 "me" 並輸出。
  5. 以字元 'm' 為分隔符分割字串並逐行輸出。

參考程式碼

using System;

class Test6
{
    public static void Main()
    {
        string str = "";
        while (str.Length <= 3)
        {
            Console.Write("請輸入一個長度大於 3 的字串:");
            str = Console.ReadLine();
        }

        // (1) 長度
        Console.WriteLine("字串長度:{0}", str.Length);

        // (2) 尋找 'a'
        int idx = str.IndexOf('a');
        if (idx >= 0)
            Console.WriteLine("第一個 'a' 的位置:{0}", idx);
        else
            Console.WriteLine("字串中不包含字母 a。");

        // (3) 插入 "hello" 於索引 3 之後(即第 4 個字元前)
        string str1 = str.Insert(3, "hello");
        Console.WriteLine("插入後:{0}", str1);

        // (4) 替換
        string str2 = str1.Replace("hello", "me");
        Console.WriteLine("替換後:{0}", str2);

        // (5) 分割
        string[] parts = str2.Split('m');
        Console.WriteLine("以 'm' 分割結果:");
        foreach (var p in parts)
            Console.WriteLine(p);
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved