C#算法实现
//求以下表达式的值,写出您想到的一种或几种实现方法: 1-2+3-4+……+m public static void GetMathInfo() { int Num = Convert.ToInt32(Console.ReadLine()); int Sum = 0; for (int i = 0; i < Num + 1; i++) { if ((i % 2) == 1) { Sum += i; } else { Sum = Sum - i; } } System.Console.WriteLine(Sum.ToString()); System.Console.ReadLine(); } //求两个数的最大公约数 public static void GetYueshu(int num1, int num2) { int min = num1 < num2 ? num1 : num2; for (int i = min; i > 1; i--) { if (num1 % i == 0 && num2 % i == 0) { Console.WriteLine(i); } } Console.ReadKey(); } //合并两个数组2 public static void UnionArray2() { String[] str1 = { "1", "2", "3" }; String[] str2 = { "2", "3", "4", "5" }; ArrayList array = new ArrayList(); array.AddRange(str1); foreach (string s in str2) { if (!array.Contains(s)) { array.Add(s); } } for (int i = 0; i < array.Count; i++) { Console.WriteLine(array[i].ToString()); } Console.ReadKey(); } //合并两个数组1 public static void UnionArray() { String[] str1 = { "1", "2", "3" }; String[] str2 = { "2", "3", "4", "5" }; string[] str3 = str1.Union(str2).Distinct().ToArray(); for (int i = 0; i < str3.Length; i++) { Console.Write(str3[i] + " "); } Console.ReadKey(); } //贷款n t年还清 每年还多少 利率s //公式:贷款*利率*(1+利率)^期数/((1+利率)^期数-1) public static void GetMh(double n, int t, double s) { double money = n * s * Math.Pow(1 + s, t) / (Math.Pow(1 + s, t) - 1); Console.WriteLine(money); Console.ReadKey(); } //数组为0到10000,求其中出现次数最多的数 private static void GetMath() { int[] hash = new int[10001]; int[] items = new int[] { 1, 3, 78, 3, 56, 10, 4, 90, 3, 1001 }; int max = 0, item = 0; for (int i = 0; i < items.Length; i++) { hash[items[i]]++; if (hash[items[i]] > max) { item = items[i]; max = hash[items[i]]; } } Console.WriteLine(item); Console.ReadKey(); } //给出一个整数数组,求其中任意两个元素之差的最大值 public static int GetMaxRang(int[] array) { int min = array[0]; int max = array[0]; foreach (int i in array) { if (i < min) { min = i; } if (i > max) { max = i; } } return max - min; } //产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复 private static void RandMethod() { int[] intArr = new int[100]; ArrayList myList = new ArrayList(); Random rnd = new Random(); while (myList.Count < 100) { int num = rnd.Next(1, 101); if (!myList.Contains(num)) myList.Add(num); } myList.Sort(); for (int i = 0; i < 100; i++) { intArr[i] = (int)myList[i]; Console.Write(intArr[i] + " "); } } // 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现。 private static int Foo(int i) { if (i < 0) return 0; if (i > 0 && i < 2) return 1; else return Foo(i - 1) + Foo(i - 2); } //冒泡排序 private static void MaoPao() { int[] array = { 2, 67, 45, 33, 54, 200 }; int temp = 0; for (int i = 0; i < array.Length - 1; i++) { for (int j = i + 1; j < array.Length; j++) { if (array[j] < array[i]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } for (int i = 0; i < array.Length; i++) { Console.Write(array[i] + " "); } Console.ReadKey(); }
?