小数的分数表示
/// <summary> /// 获取小数的分数表示 /// </summary> /// <param name="decimalPart">小数不循环部分</param> /// <param name="loopPart">小数循环部分</param> /// <returns></returns> public static string Formula(int decimalPart,int loopPart) { int u = decimalPart * ((int)Math.Pow(10,loopPart.ToString().Length) - 1) + loopPart; int d = ((int)Math.Pow(10, loopPart.ToString().Length) - 1) * (int)Math.Pow(10,decimalPart==0?0:decimalPart.ToString().Length); Debug.WriteLine("up:" + u); Debug.WriteLine("down:" + d); int maxDivisor = MaxDivisor(u, d); Debug.WriteLine("max divisor:" + maxDivisor); int u1 = u / maxDivisor; int d1 = d / maxDivisor; StringBuilder sb = new StringBuilder(); sb.Append(u1).Append("/").Append(d1); return sb.ToString(); } /// <summary> /// 获取两个数的最大公约数 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static int MaxDivisor(int a, int b) { while (a != 0 && b != 0) { //获取余数(大整数时候效率很低) int k = a % b; a = b; b = k; } return a; } public static void TestMaxDivisor() { Console.WriteLine("result:"+Formula(5, 0)); }