AI智能
改变未来

C#学习.控制台计算器类

   class Culcalator
    {
        private double NumberOne{get; set;}
        private double NumberTwo{get; set; }
        private string Oper { get; set; }//运算符变量值

       
        //开始的方法
        public void Start()
        {
            while(true)
            {
                Input();
                GetResult();
                Console.WriteLine(\”是否要继续\”);
                string input = Console.ReadLine();
                if(input == \”no\”)
                {
                    break;
                }
            }
        }

        private void Input()
        {
            this.NumberOne = ReturnInputNumber(\”请输入第一个数字\”);
            this.NumberTwo = ReturnInputNumber(\”请输入第二个数字\”);
            this.Oper = InputCulcalatorType(\”请输入运算符\”, \”+,-,*,/\”.Split(\’,\’));
        }
        /// <summary>
        /// 判断输入的是否是double类型,对的话返回数值,不对重新输入
        /// </summary>
        /// <param name=\”msg\”>输出提示</param>
        /// <returns>返回数值</returns>
        private double ReturnInputNumber(string msg)
        {
            double num;
            while (true)
            {
                Console.WriteLine(msg);
                string input = Console.ReadLine();
                
                if (double.TryParse(input, out num))
                {
                    break;
                }
                else
                {
                    Console.Write(\”输入有误,\”);
                }
            }
            return num;
        }

        private string InputCulcalatorType(string msg,params string[] opers)
        {
            string tmp;
            while(true)
            {
                Console.WriteLine(msg);
                tmp = Console.ReadLine();
                if(Array.IndexOf(opers,tmp)>=0)
                {
                    break;
                }
                else
                {
                    Console.Write(\”输入出错\”);
                }
            }
            return tmp;
        }

        private void GetResult()
        {
            double result = 0;
            switch(this.Oper)
            {
                case \”+\”:
                    result = this.NumberOne + this.NumberTwo;
                    break;
                case \”-\”:
                    result = this.NumberOne – this.NumberTwo;
                    break;
                case \”*\”:
                    result = this.NumberOne * this.NumberTwo;
                    break;
                case \”/\”:
                    result = this.NumberOne / this.NumberTwo;
                    break;
             }
            Console.WriteLine(\”{0} {1} {2} = {3}\”, this.NumberOne, this.Oper, this.NumberTwo, result);
        }
    }

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#学习.控制台计算器类