首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#中的简易计算器

问C#中的简易计算器
EN

Code Review用户
提问于 2016-06-05 17:10:58
回答 2查看 79.5K关注 0票数 6

它是一个基本的计算器,用户输入两个数字,一个操作和程序使它成为一个方程,并得到答案。例如,如果用户输入数字2,数字3,并告诉它乘,它将显示答案为6,我只是想知道如何改进。

我是否可以使用循环或更高级的程序来获得相同的输出?

代码语言:javascript
复制
 namespace Test
 {
    class Program
    {
            static void Main(string[] args)
            {
                int firstNum;
                int secondNum;                   //Variables for equation
                string operation;
                int answer;

                Console.WriteLine("Hello, welcome to Alex's basic calculator!");
                Console.ReadLine();

                Console.Write("Enter the first number in your basic equation: ");
                firstNum = Convert.ToInt32(Console.ReadLine());                             

                //User input for equation
                Console.Write("Now enter your second number in the basic equation: ");
                secondNum = Convert.ToInt32(Console.ReadLine());
                Console.Write("Ok now enter your operation ( x , / , +, -) ");
                operation = Console.ReadLine();

                if (operation == "x")
                {
                   answer = firstNum * secondNum;
                   Console.WriteLine(firstNum + " x " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                else if (operation == "/")
                {
                   answer = firstNum / secondNum;
                   Console.WriteLine(firstNum + " / " + secondNum + " = " + answer);
                   Console.ReadLine();
                }                                                                           
                //Getting answers
                else if (operation == "+")
                {
                   answer = firstNum + secondNum;
                   Console.WriteLine(firstNum + " + " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                else if (operation == "-")
                {
                   answer = firstNum - secondNum;
                   Console.WriteLine(firstNum + " - " + secondNum + " = " + answer);
                   Console.ReadLine();
                }
                else
                {
                   Console.WriteLine("Sorry that is not correct format! Please restart!");     //Catch
                   Console.ReadLine();
                }
           }
     }
}
EN

回答 2

Code Review用户

发布于 2016-06-05 17:52:18

这是个很好的开始..。

请注意,在数字提示符下输入文本(如"hello")将导致异常。有几种方法可以解决这个问题。最简单的方法是使用Int32.TryParse。下面是一个示例:

代码语言:javascript
复制
    static int PromptForInteger(string message, int minValue, int maxValue)
    {
        bool done;
        int answer = 0;

        // it will run at least once, but we don't know how many times
        do
        {
            // start with an assumption
            done = true;

            // display the prompt
            Console.Write(message);

            // check to see if what was entered "looks like" an integer
            if (Int32.TryParse(Console.ReadLine(), out answer) == false)
            {
                // display an error message, and try again
                Console.WriteLine("Could not convert your input into a whole number, please try again");
                // set our sentinel to indicate a problem
                done = false;
            } else if (answer < minValue || answer > maxValue)
            // if the value within the acceptible range?
            {
                // display an error message, and try again
                Console.WriteLine("Valid values are between {0} and {1}, please try again", minValue, maxValue);
                // set our sentinel to indicate a problem
                done = false;
            }
        } while (!done);

        // if we make it here, everything is OK
        return answer;
    }
票数 8
EN

Code Review用户

发布于 2016-06-06 13:10:50

首先,你在编写你的第一个程序方面做得很好,我在这里要强调的是,在你未来的程序中,有几件事情是有用的。

  1. 不要重复自己:在每个决策语句中,您都要多次分配变量答案,重复Console.WriteLine和Console.ReadLine。当你注意到重复时,一定要找到解决办法。
  2. 错误处理:正如每个人所指出的,当读取输入时,您需要验证或检查它们的有效性。例如,在我的主要方法中,我有以下代码行:静态void (string[] args) { //输入变量,用于计算int firstNum;int secondNum;字符串操作;字符串应答;Console.WriteLine(“你好,欢迎使用亚历克斯的基本计算器!");Console.Write(”在基本方程中输入第一个数字:“);while (!Int32.TryParse(Console.ReadLine(),out firstNum)) {Console.WriteLine(“无法处理第一个输入");Console.Write(”在基本方程中输入第一个数字:");}Console.Write(“现在在基本方程中输入第二个数字:”);while (!Int32.TryParse(Console.ReadLine(),out secondNum)) {Console.WriteLine(“无法处理第二个输入");Console.Write(”现在在基本方程中输入第二个数字:");} Console.Write("Ok现在输入您的操作(x,/,+,-)“;Console.Write= Console.ReadLine();答案=计算(firstNum,secondNum,操作);Console.WriteLine(答案);Console.ReadLine();}

注意,我使用了Int32.TryParse()来检查输入值是否可以解析为int,如果不能循环,直到得到有效的输入。开关语句中的缺省值负责操作的验证。根据您想要实现的交互,您可以为操作实现类似的东西,或者在传递不准确的结果时停止程序。

  1. 有意义的名称:对于未来的引用,最好有一个好的命名约定,比如您的命名空间和类应该描述类的使用情况。例如,类可以被命名为CalculatorSystem(Pascal )。
  2. 使用方法分组:为了使代码可重用,最好使用方法对代码进行分组。注意,C#中的方法也是Pascal情况下的。这方面的例子

我重构了您的解决方案,并创建了一个使用firstNum、secondNum和操作作为输入的计算方法,并以字符串的形式返回答案。虽然,我试图更改您的代码并使其变得简单。

代码语言:javascript
复制
 private static string Calculate(int firstNum, int secondNum, string operation)
    {
        int answer = 0;


        // Switch used as a replacement for if statement
        switch (operation)
        {
            case "x":
                answer = firstNum * secondNum;
                break;
            case "/":
                answer = firstNum / secondNum;
                break;
            case "+":
                answer = firstNum + secondNum;
                break;
            case "-":
                answer = firstNum - secondNum;
                break;
            default:
                return "Sorry that is not correct format! Please restart!";
                //  break;
        }
        return new StringBuilder(firstNum + operation + secondNum + " = " + answer).ToString();
    }

注意,我使用的是开关,而不是if语句,您可以在这里找到使用开关的优点,如果为语句的优点,则为切换。

对于良好的实践,最好将打印出来的语句隐藏到主方法中,因为稍后您可能会决定让gui应用程序显示答案并对主方法进行修改比较容易。

注意:我在"Hello,欢迎来到Alex的基本计算器“之后删除了Console.ReadLine(),因为它是多余的,您可以通过询问用户名等来做一些修改。

  1. 注释:包含评论被认为是一种很好的实践,很高兴您在控制台应用程序中吸收了它。
  2. 其他需要深入研究的有趣活动包括检查程序的行为,如果输入了浮点数、双值(会被截断),并尝试使用Environment.Exit(0)来使用户退出应用程序。祝你编码顺利。
票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/131158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档