【问题标题】:Need help Improving Basic C# Calculator [closed]需要帮助改进基本 C# 计算器 [关闭]
【发布时间】:2019-08-09 06:10:32
【问题描述】:

我制作了这个基本的 C# 计算器来反思我在过去几天学到的东西。我是一个绝对的初学者,我想得到改进和缩短它的建议。

我尝试添加 switch 语句和多个方法,但很难掌握它们。

using System;

namespace lol
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine("Hi! What is your name?");
        string name = Console.ReadLine();

        Console.WriteLine(name + " What do you wanna do?");

        Console.WriteLine("Type \"+\" for addition");
        Console.WriteLine("Type \"-\" for Subraction");
        Console.WriteLine("Type \"*\" for Multiplication");
        Console.WriteLine("Type \"/\" for division");

        string operation = Console.ReadLine();

        Console.Write("Now, Give me number one: ");
        double num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Now give me number two: ");
        double num2 = Convert.ToDouble(Console.ReadLine());

        if (operation == "+")
        {
            Console.WriteLine(num1 + num2);
        }
        else if (operation == "-")
        {
            Console.WriteLine(num1 - num2);
        }

        else if (operation == "*")
        {
            Console.WriteLine(num1 * num2);
        }

        else
        {
            Console.WriteLine(num1 / num2);

        }

    }
  }
}

【问题讨论】:

  • 我认为计算器不需要知道你的名字。
  • 你可以用 switch 代替 if ,否则其他的看起来没问题
  • 您能否展示您尝试过的那些“switch 语句”和“方法”,并说明您遇到的问题?
  • @FalcoGer 是的,但我只是想在其中添加尽可能多的东西。老实说,我觉得写一个合适的第一个程序有点太兴奋了。
  • 可以使用枚举来代替字符串比较

标签: c# code-cleanup


【解决方案1】:

如果对你的眼睛更好,你可以这样写:

static class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hi! What is your name?");
        string name = Console.ReadLine();

        Console.WriteLine(name + " What do you wanna do?");
        string[] operations = new string[] { "\"+\" for addition", "\"-\" for subtraction", "\"*\" for multiplication", "\"/\" for divsion" };
        foreach (string operation in operations) { Console.WriteLine("Type " + operation); }

        string cmd = Console.ReadLine();

        Console.Write("Now, Give me number one: ");
        double num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Now give me number two: ");
        double num2 = Convert.ToDouble(Console.ReadLine());

        switch (cmd)
        {
            case "+": Console.WriteLine(num1 + num2); break;
            case "-": Console.WriteLine(num1 - num2); break;
            case "*": Console.WriteLine(num1 * num2); break;
            case "/": Console.WriteLine(num1 / num2); break;
        }
    }
}

【讨论】:

  • 这确实有帮助!我仍然是初学者,所以我必须了解您在那里所做的一些事情。不过谢谢!
【解决方案2】:

使用枚举并检查用户输入是否有效。我还添加了一个循环来检查用户是否想要输入方程式。 参考资料:

你可以在这里试试:https://dotnetfiddle.net/aIwX5P

using System;

public class Program
{
    enum eOperator
    {
        opAdd = 0,
        opSub = 1,
        opDiv = 2,
        opMul = 3,
        opInvalid = int.MinValue + 1,
        opQuit = int.MinValue
    }
    public static void Main()
    {
        double a = 0.0, b = 0.0;
        eOperator op = eOperator.opQuit;
        string input = String.Empty;
        Console.WriteLine("Calculator");
        Console.WriteLine("Enter 'quit' at any time to exit.");
        // repeat until the user wants to quit.
        do // while(op != eOperator.opQuit)
        {
            Console.Write("a = ");
            input = Console.ReadLine().ToLower().Trim();
            if (double.TryParse(input, out a))
            {
                // input is a valid double and was stored in a
                Console.Write("Operator: ");
                input = Console.ReadLine().ToLower().Trim();
                switch (input)
                {
                    case "+":
                        op = eOperator.opAdd;
                        break;
                    case "-":
                        op = eOperator.opSub;
                        break;
                    case "*":
                        op = eOperator.opMul;
                        break;
                    case "/":
                        op = eOperator.opDiv;
                        break;
                    case "quit":
                        op = eOperator.opQuit;
                        break;
                    default:
                        op = eOperator.opInvalid; // can't be left as quit
                        Console.WriteLine("Invalid entry. +, -, *, / or quit for operator.");
                        break;
                }
                if (op != eOperator.opQuit && op != eOperator.opInvalid)
                {
                    // user didn't choose to quit or type something invalid
                    Console.Write("b = ");
                    input = Console.ReadLine().ToLower().Trim();
                    if (double.TryParse(input, out b))
                    {
                        // input is a valid double and was parsed into b
                        double result = a; // we use the operator on a, so we might as well just store a into the result right away.
                        // do the operation on result.
                        switch (op)
                        {
                            case eOperator.opAdd:
                                result += b;
                                break;
                            case eOperator.opSub:
                                result -= b;
                                break;
                            case eOperator.opMul:
                                result *= b;
                                break;
                            case eOperator.opDiv:
                                // Div by 0 check. without this, this still works since double has +/- inf values.
                                if (b != 0.0) // comparing double with = and != is usually bad idea, but 0.0 is saved without rounding errors.
                                {
                                    result /= b;
                                }
                                else
                                {
                                    Console.WriteLine("Div by 0");
                                    op = eOperator.opInvalid;
                                }
                                break;
                            default:
                                // this if branch checked for the other two operators. since we never chanced op after that check, this exception should never happen.
                                // it is still a good idea to include it to find errors in your logic, should they have occurred.
                                throw new Exception("This shouldn't happen.");
                        }
                        if (op != eOperator.opInvalid)
                        {
                            Console.WriteLine("Result: " + result.ToString());
                        }
                        // the only invalid operation is div by 0 for now. the message was sent to the user in that case, so no else is needed at this point.
                        // alternatively you can store an error message into a string, and when op = opInvalid, then display that error message here centralized.
                        // this would be a good idea if multiple things can go wrong.
                    }
                    else if (input == "quit")
                    {
                        // input for b was an invalid number, but input was 'quit'
                        op = eOperator.opQuit;
                    }
                    else
                    {
                        // input for b was an invalid number and also not 'quit', display error message
                        Console.WriteLine("Invalid entry. Type a number or Quit");
                    }
                }
            }
            else if (input == "quit")
            {
                // input for a was invalid number, but 'quit'
                op = eOperator.opQuit;
            }
            else
            {
                // input for a was invalid number and also not 'quit'
                Console.WriteLine("Invalid entry. Type a number or Quit");
            }
        // repeat until the user wants to quit.
        }while(op != eOperator.opQuit);
        Console.WriteLine("Bye");
    }
}

【讨论】:

  • 谢谢!我会调查并搜索这些主题。
  • 我会这么说。看起来真的很高级。
  • 如果你想进阶,你可以试试方程解析:P
  • @AhmadDaPenguinz 我包含一些指向 msdn 的链接,用于枚举、选择案例语句和使用 tryparse 进行输入检查。
猜你喜欢
  • 2021-11-12
  • 2012-10-03
  • 1970-01-01
  • 2011-09-15
  • 2014-08-31
  • 2012-07-12
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多