c#编程练习

目录

练习 1: 数组元素求和

练习2: 数组元素乘积

练习3: 数组元素平均值

练习4: 查找数组中的最大值

练习 5: 查找数组中的偶数

练习6: 计算阶乘

练习7: 数组翻转

练习8: 字符串反转

练习9: 检查回文

练习 10 : 数组中的最大值和最小值

练习 11: 素数检查器

练习 12: 字符串中的最长无重复子串

练习 13: 数字到英文转换

练习 14: 简单的日期格式化

练习 15: 简单的计算器

练习 16: 数组中的两数之和

练习 17: 字符串去重

练习 18: 滑动窗口最大值

练习 19: 矩阵旋转

练习20 : 字符串压缩

练习21: 有效的括号序列

练习22: 最长公共前缀


练习 1: 数组元素求和

题目 : 编写一个C#程序,计算数组中所有元素的总和。

using  System;
class  ArraySum  
{
    public static int SumArray(int[] arr)
    {
        //答案代码. . . . . .
         int sum = 0;
         foreach (var i in arr)
         {
              sum += i;
         }
         return sum;
    }
    static void Main(string[] args)
    {
    int[] numbers = { 1, 2, 3, 4, 5 };
    Console.WriteLine(SumArray(numbers)); //Ⅱ 应输出 15
    }
}

结果如图:

练习2: 数组元素乘积

题目 : 编写一个C#程序,计算数组中所有元素的乘积。

using  System;
class  ArrayProduct  {
    public static long ProductArray(int[] arr)
    {
        //答案代码. . . . . .
        int a = 1;
        foreach (var item in arr)
        {
            a *= item;
        }
        return a;
    }
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        Console.WriteLine(ProductArray(numbers)); //Ⅱ 应输出 120
    }
}

结果如图:

练习3: 数组元素平均值

题目 : 编写一个C#程序,计算数组中所有元素的平均值。

using  System;
class  ArrayAverage  {
    public static double AverageArray(int[] arr)
    {
        //答案代码. . . . . .
        int sum = 0;
        foreach (int i in arr)
        {
            sum += i;
        }
        int avg = sum / arr.Length;
        return avg;
    }
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        Console.WriteLine(AverageArray(numbers)); //Ⅱ 应输出 3
    }
}

结果如图:

练习4: 查找数组中的最大值

题目 : 编写一个C#程序,找到数组中的最大值。

using  System;
class  ArrayMax  {
 public static int MaxValue(int[] arr)
 {
     //答案代码. . . . . .
     for (int i = 0; i < arr.Length - 1; i++)
     {
         if(arr[i] > arr[i + 1])
         {
             int temp = arr[i];
             arr[i] = arr[i + 1];
             arr[i + 1] = temp;
         }
     }
     int max = arr[arr.Length - 1];
     return max;
 }
 static void Main(string[] args)
 {
     int[] numbers = { 1, 2, 3, 4, 5 };
     Console.WriteLine(MaxValue(numbers)); //Ⅱ 应输出 5
 }
}

结果如图:

练习 5: 查找数组中的偶数

题目 : 编写一个C#程序,从数组中筛选出所有的偶数,并返回一个新的数组。

using  System;using  System .Collections .Generic;
class  EvenNumbers  {
    public static List<int> GetEvens(int[] arr)
    {
        List<int> evens = new List<int>();
        foreach (int num in arr)
        {
            if (num % 2 == 0)   
            {
                evens.Add(num);   
            }
        }
        return evens;   
    }
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6 };
        List<int> evenNumbers = GetEvens(numbers);
        foreach (int num in evenNumbers)
        {
            Console.Write(num + "  ");
        }//Ⅱ 应输出 2  4  6、
    }
}

结果如图:

练习6: 计算阶乘

题目 : 编写一个C#函数,计算给定非负整数的阶乘。

using  System;
class  Factorial  {
    public static long CalculateFactorial(int number)
    {
        //答案代码. . . . . .
        if (number == 1 || number == 0)
        {
            return 1;
        }
        int a = 1;
        for (int i = number; i > 1; i--)
        {
            a = a * i;
        }
        return a;
    }
    static void Main(string[] args)
    {
        Console.WriteLine(CalculateFactorial(5)); //Ⅱ 应输出 120 
    }
}

结果如图:

练习7: 数组翻转

题目 : 编写一个C#程序,将一个整数数组翻转。

using  System;
class  ArrayReverse  {
 public static void ReverseArray(int[] arr)
 {
    //第一种方法
     /*int left = 0;  
     int right = arr.Length - 1;
     while (left < right)
     {
         int temp = arr[left];
         arr[left] = arr[right];
         arr[right] = temp;
         left++;
         right--;
     }*/
    //第二种方法
    int[] a = new int[arr.Length];
    Array.Reverse(arr);
 }
 static void Main(string[] args)
 {
     int[] array = { 1, 2, 3, 4, 5 };
     ReverseArray(array);
     foreach (int i in array)
     {
         Console.Write(i + "  ");
     }//Ⅱ 应输出 5  4  3  2  1
 }
}

结果如图:

练习8: 字符串反转

题目 : 编写一个C#函数,反转一个字符串。

using  System;
class  StringReversal  {
    public static string ReverseString(string str)
    {
        string a = new string(str.Reverse().ToArray());
        return a;
    }
    static void Main(string[] args)
    {
        Console.WriteLine(ReverseString("hello")); //Ⅱ 应输出 olleh
    }
}

结果如图:

练习9: 检查回文

题目 : 编写一个C#函数,检查一个字符串是否是回文。

using  System;
class  PalindromeChecker  {
    public static bool IsPalindrome(string str)
    {
        //答案代码. . . . . .
        string a = new string(str.Reverse().ToArray());
        if (a.Equals(str))
        {
            return true;
        }
        return false;
    }
    static void Main(string[] args)
    {
        Console.WriteLine(IsPalindrome("racecar")); //Ⅱ 应输出 True
    }
}

结果如图:

练习 10 : 数组中的最大值和最小值

题目 : 编写一个C#函数,找出数组中的最大值和最小值。

using  System;
class  MaxMinFinder  {
    public static Tuple<int, int> FindMaxMin(int[] arr)
    {
        //答案代码. . . . . .
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }    
        }
        int max = arr[arr.Length - 1];
        int min = arr[0];
        Tuple<int, int> tuple = new Tuple<int, int>(max, min);
        return tuple;
    }
    static void Main(string[] args)
    {
        int[] array = { 3, 7, 1, 9, 2 };
        var result = FindMaxMin(array);
        Console.WriteLine($"Max :  {result.Item1} ,  Min :  {result.Item2}");
    //Ⅱ 应输 出 Max :  9 ,  Min: 1
    } 
}

结果如图:

练习 11: 素数检查器

题目 : 编写一个C#函数,用于判断一个数字是否为素数。

using  System .Security.Cryptography;
using  System .Text; using  System . Linq;
using  System .Collections .Generic; using  System .Diagnostics;
using  System .Numerics; using  System;
class  PrimeChecker  {
public static bool IsPrime(int number)
{
    //答案代码. . . . . .
    if(number < 2) //小于2的不是质数
    {
        return false;
    }
    for (int i = 2; i < number; i++)
    {
        if (number % i == 0)
        {
            return false;    
        }
    }
    return true;
}
static void Main(string[] args)
{
    Console.WriteLine(IsPrime(17)); //Ⅱ 应输出 True
}
}

结果如图:

练习 12: 字符串中的最长无重复子串

题目 : 找到一个字符串中的最长无重复字符的子串长度。

using  System;
class  LongestUniqueSubstring  {
    public static int LengthOfLongestSubstring(string s)
    {
        //答案代码. . . . . .
        if (string.IsNullOrEmpty(s)) return 0;
        int maxLength = 0;
        int left = 0; // 滑动窗口的左边界  
        HashSet<char> cs = new HashSet<char>(); 
        for (int right = 0; right < s.Length; right++)
        {
            // 尝试扩展右边界  
            while (cs.Contains(s[right]))
            {
                // 如果当前字符已经在集合中,则移动左边界,并从集合中移除左边界的字符  
                cs.Remove(s[left]);
                left++;
            }
            // 添加当前字符到集合中,并更新最大长度  
            cs.Add(s[right]);
            maxLength = Math.Max(maxLength, right - left + 1);
        }
        return maxLength;
    }
    static void Main(string[] args)
    {
        Console.WriteLine(LengthOfLongestSubstring("abcabcbb")); //Ⅱ 应输出 3 
    }
}

结果如图:

练习 13: 数字到英文转换

题目 : 编写一个函数,将一个整数转换为其英文描述。

using  System;
class  NumberToWords  {
public static string ConvertNumberToWords(int number)
{
    //答案代码. . . . . .
    if (number == 0) return "Zero";
    string[] ones = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
                    "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    string[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    if (number < 20) return ones[number];
    if (number < 100) return tens[number / 10] + (number % 10 != 0 ? " " + ones[number % 10] : "");
    if (number < 1000)
    {
        int h = number / 100;
        int s = number % 100;
        return ones[h] + " Hundred" + (s != 0 ? " " + ConvertNumberToWords(s) : " ");
    }
    // 注意:这里只处理到999,对于更大的数字,需要添加额外的逻辑  
    throw new ArgumentException("Number is out of range for this method.");
}
static void Main(string[] args)
{
    Console.WriteLine(ConvertNumberToWords(15)); //Ⅱ 应输出 "Fifteen " 
}
}

结果如图:

练习 14: 简单的日期格式化

题目 : 编写一个函数,将当前日期格式化为“Day Month Year”形式。

using  System;
class  DateFormatter  {
 public static string FormatDate()
 {
     //答案代码. . . . . .
     DateTime dateTime = DateTime.Now;
     string date = string.Format("{0} {1}月 {2}", dateTime.Day, dateTime.Month, dateTime.Year);
     return date;
 }
 static void Main(string[] args)
 {
     Console.WriteLine(FormatDate()); //Ⅱ 输出类似 "5  7月 2024 "
 }
}

结果如图:

练习 15: 简单的计算器

题目 : 编写一个简单的计算器函数,支持加、减、乘、除四种基本运算。

using  System;
class  SimpleCalculator  {
    public static double Calculate(double num1, string op, double num2)
    {
        //答案代码. . . . . .
        double a = 0;
        switch(op)
        {
            case "+":
                a = num1 + num2;
                break;
            case "-":
                a = num1 - num2;
                break;
            case "*":
                a = num1 * num2;
                break;
            case "/":
                a = num1 / num2;
                break;
        }
        return a;    
    }
    static void Main(string[] args)
    {
        Console.WriteLine(Calculate(10,"+", 5)); //Ⅱ 应输出 15
        Console.WriteLine(Calculate(10, "-", 5)); //Ⅱ 应输出 5
        Console.WriteLine(Calculate(10, "*", 5)); //Ⅱ 应输出 50
        Console.WriteLine(Calculate(10, "/", 5)); //Ⅱ 应输出 2
    }
}

结果如图:

练习 16: 数组中的两数之和

题目 : 给定一个整数数组 nums  和一个目标值 target ,编写一个函数找到数组中和为目标值的两个整数的索 引。假设数组中的数据和一定能满足target,不用考虑不满足的情况。

using  System;
using  System .Collections .Generic;
class TwoSum
{
   public static Tuple<int, int> FindTwoSum(int[] nums, int target)
   {
       //答案代码. . . . . .
       int Item1 = 0;
       int Item2 = 0;
       for (int i = 0; i < nums.Length; i++)
       {
           for(int j = 0;j < nums.Length; j++)
           {
               if (nums[i] + nums[j] == target && nums[i] != nums[j])
               {
                   Item1 = i;
                   Item2 = j;
               }
           }
       }
       return Tuple.Create(Item1, Item2);
   }
   static void Main(string[] args)
   {
       int[] nums = { 2, 7, 11, 15 };
       int target = 9;
       var indices = FindTwoSum(nums, target);
       Console.WriteLine($"Indices :  {indices.Item1} ,  {indices.Item2}"); 
       //Ⅱ 应输 出 Indices :  0 ,  1
   }
}

结果如图:

练习 17: 字符串去重

题目 : 编写一个函数,移除字符串中的重复字符,只保留第一个出现的字符。

using  System;
using  System .Text;
class  UniqueChars  {
    public static string RemoveDuplicates(string str)
    {
        //答案代码. . . . . .
        HashSet<string> list = new HashSet<string>();
        foreach (var item in str)
        {
            list.Add(item.ToString());
        }
        string[] arr = list.ToArray();
        string a = "";
        foreach (var item in arr)
        {
            a += item.ToString();
        }
        return a;
    }
    static void Main(string[] args)
    {
        string input = "hello  world ";
        Console.WriteLine(RemoveDuplicates(input)); //Ⅱ 应输出 helo wrd
    }
}

结果如图:

练习 18: 滑动窗口最大值

题目 : 给定一个数组和一个窗口大小k,找到滑动窗口中的最大值。

using  System;
using  System .Collections .Generic;
class  SlidingWindowMax  {
    public static List<int> FindMaxInWindows(int[] nums, int k)
    {
        //答案代码. . . . . .
        List<int> result = new List<int>();
        int max = nums[0];
        int left = 0;
        for (int i = 1; i < k; i++)
        {
            max = Math.Max(max, nums[i]);
        }
        result.Add(max);
        for (int i = k; i< nums.Length; i++)
        {
            left++;
            for (int j = left; j < left + k; j++)
            {
                max = Math.Max(max, nums[j]);
            }
            result.Add(max);
        }
        return  result;
    }
    static void Main(string[] args)
    {
        int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 }; 
        int k = 3;
        List<int> maxValues = FindMaxInWindows(nums, k); 
        foreach (int max in maxValues)
        {
            Console.Write(max + "  ");
        }
        //Ⅱ 应输出 3  3  5  5  6  7
    }
}

结果如图:

练习 19: 矩阵旋转

题目 : 编写一个函数,将一个N x N的矩阵顺时针旋转90度。

using  System;
class  MatrixRotation  {
    public static void RotateMatrix(int[,] matrix)
    {
        //答案代码. . . . . .
        int n = matrix.GetLength(0);
        int m = matrix.GetLength(1);
        int[,] b = new int[n, m];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                b[i, j] = matrix[n - 1 -j, i];
            }
        }
        for(int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                matrix[i,j] = b[i, j];
            }
        }
    }
    static void PrintMatrix(int[,] matrix)
    {
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + "  ");
            }
            Console.WriteLine();
        }
    }
    static void Main()
    {
        int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        RotateMatrix(matrix); PrintMatrix(matrix);
        //Ⅱ 应输出 : Ⅱ  7  4  1   Ⅱ  8  5  2   Ⅱ  9  6  3
    }
}

结果如图:

接下来是五个中等难度的综合题,这些题目将挑战你在C#中运用数组、字符串、循环、条件语句和算法的能力:

练习20 : 字符串压缩

题目 : 编写一个函数,对字符串进行基本的压缩,如果压缩后的字符串不比原字符串短,则返回原字符串。

using  System .Text;
class  StringCompressor  {
     public static string CompressString(string str)
     {
         //答案代码. . . . . .
         if (string.IsNullOrEmpty(str)) return "";
         //StringBuilder提供了一个可变的字符序列,可以进行修改
         StringBuilder str2 = new StringBuilder();
         char a = str[0];
         int count = 1;
         for (int i = 1; i < str.Length; i++)
         {
             if (str[i] == a)
             {
                 count++;
             }
             else
             {
                 str2.Append(a);
                 str2.Append(count);
                 a = str[i];
                 count = 1;
             }
         }
         // 添加最后一个字符及其计数  
         str2.Append(a);
         str2.Append(count);
         if (str2.Length > str.Length)
         {
             return str.ToString();
         }
         return str2.ToString();
     }
     static void Main(string[] args)
     {
         Console.WriteLine(CompressString("aabcccccaaa")); //Ⅱ 应输出 "a2b1c5a3 " 
     }
}

结果如图:

练习21: 有效的括号序列

题目 : 编写一个函数,检查括号序列是否有效。有效的括号序列要求每对括号都能正确闭合。

using  System;
class  ValidParentheses  {
    public static bool IsValid(string s)
    {
        //答案代码. . . . . .
        Stack<char> chars = new Stack<char>();
        foreach (char c in s)
        {
            if(c =='(' || c =='[' || c == '{')
            {
                chars.Push(c);
            }
            else if(c == ')'|| c == ']' || c == '}')
            {
                if(chars.Count == 0)
                {
                    return false;
                }
                char a = chars.Pop();
                if(c ==  ')' &&  a != '(')
                {
                    return false;
                }
                if (c == ']' && a != '[')
                {
                    return false;
                }
                if (c == '}' && a != '{')
                {
                    return false;
                }
            }
        }
        return chars.Count == 0;
}
    static void Main(string[] args)
    {
        Console.WriteLine(IsValid("()[]{}")); //Ⅱ 应输出 True 
    }
}

结果如图:

练习22: 最长公共前缀

题目 : 编写一个函数,找出一组字符串中的最长公共前缀。

using  System .Security.Cryptography;
using  System .Text; using  System . Linq;
using  System .Collections .Generic; using  System .Diagnostics;
using  System .Numerics; using  System;
class  LongestCommonPrefix  {
 public static string FindLongestCommonPrefix(string[] strs)
 {
     //答案代码. . . . . .
     if (strs == null || strs.Length == 0) return "";
     string p = strs[0];
     for (int i = 1; i < strs.Length; i++)
     {
         int j = 0;
         while ( j < p.Length && j < strs[i].Length && p[j] == strs[i][j])
         {
             j++;
         }
         p = p.Substring(0,j);
         if (p.Length == 0)
         {
             break;
         }
     }
     return p;
 }
 static void Main(string[] args)
 {
     string[] strs = { "flower ", "flow ", "flight " };
     Console.WriteLine(FindLongestCommonPrefix(strs)); //Ⅱ 应输出 "fl " 
 }
}

结果如图:

  • 11
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值