写一个读取数字的类 实现输入小于max参数的数,实现输入介于min和max之间的数字,实现输入一个整数,使用指定默认参数代替了方法重载。
代码:
class JKConsole { public static int ReadInt(int max = int.MaxValue, int min = int.MinValue) { if (max!=int.MaxValue && min==int.MinValue) { min = 0; } if (max!=int.MaxValue && min!=int.MinValue) { if (max>min) { int temp = max; max = min; min = temp; } } int num=0; do { Console.WriteLine("请输入一个数字"); string str = Console.ReadLine(); if (int.TryParse(str,out num)) { if (num>min &&num <max) { return num; } else { Console.Write("输入的数字不在{0}-{1}范围内", min, max); continue; } } Console.Write("输入的格式有误"); } while (true); } }
class Program { static void Main(string[] args) { int num = JKLibrary.NumberHelper.JKConsole.ReadInt(0, 100); int num1 = JKLibrary.NumberHelper.JKConsole.ReadInt(100); int num2 = JKLibrary.NumberHelper.JKConsole.ReadInt(); } }
新增知识点:命名空间可以嵌套
namespace n1 { namespace n2 { namespace n3 { class c { } } } //等价于 namespace n1.n2.n3 { class c { }
快速排序法
class Program { static void Main(string[] args) { int[] array = { 1,3,4,7,2,7,9,0,-13}; Sort(array, 0, array.Length - 1); foreach (var item in array) { Console.Write(item + " "); } Console.ReadKey(); } static int GetIndex(int[] array, int leftIndex, int rightIndex) { int luler = array[leftIndex]; while (leftIndex < rightIndex) { while (leftIndex<rightIndex &&array[rightIndex]>luler) { rightIndex--; } if (leftIndex<rightIndex) { array[leftIndex] = array[rightIndex]; leftIndex++; } while(leftIndex<rightIndex && array[leftIndex]<luler){ leftIndex++; } if (leftIndex<rightIndex){ array[rightIndex] = array[leftIndex]; rightIndex--; } } array[leftIndex] = luler; return leftIndex; } static void Sort(int[] array, int left, int right) { if (left<right) { int temp = GetIndex(array, left, right); Sort(array,left,temp-1); Sort(array, temp + 1, right); } } }
继承,构造方法的执行顺序内等容前面博客已经记载,此处省略