Нужна помощь в улучшении базового калькулятора С#

Я сделал этот базовый калькулятор 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);

        }

    }
  }
}

person AhmadDaPenguinz    schedule 09.08.2019    source источник
comment
Не думаю, что калькулятору нужно знать ваше имя.   -  person FalcoGer    schedule 09.08.2019
comment
вы можете использовать переключатель вместо if , иначе все выглядит нормально   -  person Pranay Rana    schedule 09.08.2019
comment
Не могли бы вы показать те операторы и методы switch, которые вы пробовали, и рассказать о проблемах, с которыми вы с ними столкнулись?   -  person Hans Kesting    schedule 09.08.2019
comment
@FalcoGer да, но я просто пытался добавить сюда как можно больше необходимого. Честно говоря, я думаю, что слишком увлекся написанием правильной первой программы.   -  person AhmadDaPenguinz    schedule 09.08.2019
comment
вместо сравнения строк вы можете использовать перечисления для операции   -  person FalcoGer    schedule 09.08.2019
comment
вы можете сделать проверку ввода.   -  person FalcoGer    schedule 09.08.2019
comment
@HansKefing, к сожалению, я их не сохранил. Как только я закончил код, я заменил его на Switch, и он почему-то не работал, поэтому я изменил их обратно на if. В следующий раз я буду осторожен, чтобы записать их, извините!   -  person AhmadDaPenguinz    schedule 09.08.2019
comment
@FalcoGer Не могли бы вы объяснить это?   -  person AhmadDaPenguinz    schedule 09.08.2019
comment
Предлагаемое расширение: попробуйте, что произойдет, когда вы введете aa вместо числа или 0 для второго числа и $ для операции, а затем предотвратите сбой вашего приложения из-за этих ошибок.   -  person Hans Kesting    schedule 09.08.2019
comment
Прямо сейчас недопустимый ввод (скажем, написание приветствия вместо числа) приведет к сбою вашей программы. Лучше напечатать что-то вроде «привет» — это не число, попробуйте еще раз. вместо краха :)   -  person Luaan    schedule 09.08.2019
comment
@Luann Я пытался это сделать, но мне было трудно понять, как это сделать. Извините, что звучу так глупо, но не могли бы вы сказать мне, как я могу добавить это? Благодарю вас!   -  person AhmadDaPenguinz    schedule 09.08.2019
comment
@HansKesting Спасибо за предложение!   -  person AhmadDaPenguinz    schedule 09.08.2019
comment
Этот вопрос не относится к этому сайту, так как он основан на мнении. Однако не стесняйтесь спрашивать на Code Review, который создан именно для таких вопросов.   -  person Martin Verjans    schedule 09.08.2019
comment
Почему все говорят «дополнение»?   -  person Andrew Truckle    schedule 09.08.2019
comment
@MartinVerjans, спасибо за это. Я здесь совсем новичок, поэтому я этого не знал. Я бы взял мои будущие вопросы, подобные этому, там. Спасибо!   -  person AhmadDaPenguinz    schedule 09.08.2019
comment
Использование ifs в порядке, между ifs и регистром переключения есть небольшая производительность. Особенно неважно, что вы используете в малых или средних проектах, даже огромных. Ваш код в порядке.   -  person Mert Akkanat    schedule 09.08.2019
comment
@AndrewTruckle Мне очень жаль, что я не заметил эту ошибку раньше. Спасибо, что указали на это!   -  person AhmadDaPenguinz    schedule 09.08.2019


Ответы (2)


Если так лучше для ваших глаз, вы можете написать так:

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;
        }
    }
}
person Mar Tin    schedule 09.08.2019
comment
Это, безусловно, помогает! Я все еще новичок, поэтому мне нужно понять некоторые вещи, которые вы там делали. Но спасибо! - person AhmadDaPenguinz; 09.08.2019

Использование перечислений и проверка правильности ввода пользователя. Я также добавил цикл, который проверяет, хочет ли пользователь вводить уравнения. Использованная литература:

Вы можете попробовать это здесь: 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");
    }
}
person FalcoGer    schedule 09.08.2019
comment
Спасибо вам за это! Я посмотрю на это и поищу эти темы. - person AhmadDaPenguinz; 09.08.2019
comment
Я скажу это, хотя. Это выглядит действительно продвинутым. - person AhmadDaPenguinz; 09.08.2019
comment
если вы хотите продвинутого, вы можете попробовать синтаксический анализ уравнения: P - person FalcoGer; 09.08.2019
comment
@AhmadDaPenguinz Я включил несколько ссылок на msdn для перечислений, выбора операторов case и проверки ввода с помощью tryparse. - person FalcoGer; 09.08.2019