C#实现将输入的数自动转换为科学计数法

时间:2023-12-11 15:09:02

一朋友写了一个把输入的整型或浮点数转换为科学计数法表示的算法,写好后叫我去帮他看看有没有什么bug之类的没有考虑周全。我还没有细看就已经把我吓到了----整整写了将近三百行代码。我也没说他什么,只是回到我的电脑前自己写了一个试试。

需求:输入一个数,用科学计数法表示,要有三位有效数字,幂数部分也要求是三位,不足则补零

代码如下:

public abstract class ScienceCount
    {
        public static string KXJSF(double num)
        {
            double bef =System.Math.Abs(num);
            int aft=0;
            while (bef >= 10 ||(bef < 1&& bef!=0))
            {
                if (bef >= 10)
                {
                    bef = bef / 10;
                    aft++;
                }
                else
                {
                    bef = bef * 10;
                    aft--;
                }
            }
            return string.Concat(num>=0?"":"-",ReturnBef(bef),"E",ReturnAft(aft));
        }
        /// <summary>
        /// 有效数字的处理
        /// </summary>
        /// <param name="bef">有效数字</param>
        /// <returns>三位有效数字,不足则补零</returns>
        public static string ReturnBef(double bef)
        {
            if (bef.ToString() != null)
            {
                char[] arr = bef.ToString().ToCharArray();
                switch (arr.Length)
                {
                    case 1:
                    case 2: return string.Concat(arr[0] , "." , "00"); break;
                    case 3: return string.Concat(arr[0] + "." + arr[2] + "0"); break;
                    default: return string.Concat(arr[0] + "." + arr[2] + arr[3]); break;
                }
            }
            else
                return "000";
        }
        /// <summary>
        /// 幂的处理
        /// </summary>
        /// <param name="aft">幂数</param>
        /// <returns>三位幂数部分,不足则补零</returns>
        public static string ReturnAft(int aft)
        {
            if (aft.ToString() != null)
            {
                string end;
                char[] arr = System.Math.Abs(aft).ToString().ToCharArray();
                switch (arr.Length)
                {
                    case 1: end = "00" + arr[0]; break;
                    case 2: end = "0" + arr[0] + arr[1]; break;
                    default: end = System.Math.Abs(aft).ToString(); break;
                }
                return string.Concat(aft >= 0 ? "+" : "-" , end);
            }
            else
                return "+000";
        }
    }

调用代码:

static void Main()
 {
            string num = "0";
            while (num != "#")
            {
                num = Console.ReadLine();
                if(!string.IsNullOrEmpty(num.Trim()))
                    Console.WriteLine(ScienceCount.KXJSF(double.Parse(num)));
            }

}

代码可运行,且基本满足要求(没有考虑输入字符的情况),若有不足请各位看客慷慨指出。