递归:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Console.WriteLine("输入一个数,计算阶乘"); int m = int.Parse(Console.ReadLine()); int sumc = 0; for (int i = 0; i <= m; i++) { sumc += fun(i); } for (int i = 0; i < m; i++) { Console.Write("{0}!+", i); } Console.WriteLine("{0}!={1}", m, sumc); Console.ReadLine(); } public static int fun(int n) { if (n < 1) { return 0; } if (n == 1) { return 1; } return n * fun(n - 1); } } }
实现IComparable和必需的CompareTo方法。
public class Temperature:IComparable { protected double TemperatureF; public int CompareTo(object obj) { if (obj == null) return 1; Temperature otherTemprature = obj as Temperature; if (otherTemprature != null) return this.TemperatureF.CompareTo(otherTemprature.TemperatureF); else throw new ArgumentException("Object is not a Temperature"); } public double Fahrenheit { get { return this.TemperatureF; } set { this.TemperatureF=value;} } public double Celsius { get { return (this.TemperatureF-32)*(5.0/9); } set { this.TemperatureF = (value *9.0/5)+32; } } } static void Main(string[] args) { ArrayList temperatures = new ArrayList(); Random random = new Random(); for (int i = 0; i < 10; i++) { int degrees = random.Next(0, 100); Temperature temp = new Temperature(); temp.Fahrenheit = degrees; temperatures.Add(temp); } temperatures.Sort(); foreach (Temperature item in temperatures) { Console.WriteLine(item.Fahrenheit); } }