课后作业 06 -- 小数后几位精确判断并输出

            Console.Write("输入您要精确的小数:");
            string strA = Console.ReadLine();
            Console.Write("您要精确到几位小数:");
            int k = int.Parse(Console.ReadLine());
            double n = Convert.ToDouble(strA);
            int i = strA.IndexOf(".");//确定小数索引位置
            string strB = string.Empty;
            try
            {
                strB = strA.Substring(i + k + 1, 1);//截取精确小数的后一位

                int m = int.Parse(strB);
                string strC = strA.Substring(i + 1, k);//截取要保留的小数部分

                double j = Math.Floor(n);
                strA = Convert.ToString(j);//提取其整数部分

                strA = strA + "." + strC;//整数加要精确的小数部分
                double q = Convert.ToDouble(strA);
                Console.Write("精确后的数为:");
                if (m >= 5)
                    Console.Write(q + Math.Pow(0.1, k));//五入
                else
                    Console.Write(q);
            }
            catch
            {
                Console.WriteLine("精确的小数位要大于您输入数的小数数!");
            }
            Console.ReadLine();

  

posted @ 2015-08-08 00:22  WhyToHow  阅读(175)  评论(1编辑  收藏  举报