N
N
NikitaSova2020-06-10 13:47:35
C++ / C#
NikitaSova, 2020-06-10 13:47:35

How to make a calculator not through case but through if C#?

I recently made a calculator with functions and a case method. But now I need to change it to if. I wanted to ask you how this can be done.
Thanks in advance
Here is the code:

public static int Nikita(int a, int b, char d)
{
  switch (d)
  {
    case '+':
      return a + b;
    case '-':
      return a - b;
    case '*':
      return a * b;
    case '/':
      return a / b;
    default:
       Console.WriteLine("Ошибка");
       break;
  }
  return a - b;
}

static void Main(string[] args)
{   
  {
    Console.Write("вевдите первое число: ");
    int am = (int)Convert.ToInt64(Console.ReadLine());
    Console.Write("введите знак: ");
    char dm = Convert.ToChar(Console.ReadLine());
    Console.Write("введите второе число: ");
    int bm = (int)Convert.ToInt64(Console.ReadLine());
    int resault = Nikita(am, bm, dm);
    Console.WriteLine(resault);

  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
edward_freedom, 2020-06-10
@edward_freedom

delegate int Math(int x, int y); //вынеси в глобальные переменные

 var actions = new Dictionary<string, Math>()
            {
                {"+", (x, y) => x + y},
                {"-", (x, y) => x - y},
                {"/", (x, y) => x / y},
                {"*", (x, y) => x * y},
            };
            var random = new Random();
            foreach (var action in actions)
            {
                var x = random.Next(1, 100);
                var y = random.Next(1, 100);
                Debug.WriteLine($"{x} {action.Key} {y} = {action.Value(x, y)}");
            }

1
1SLY2, 2020-06-11
@1SLY2

NikitaSova :

int Func(int num1, int num2, char oper){
if(oper == "+"){
  return num1 + num2;
}
if(oper == "-"){
  return num1 - num2;
}
if(oper == "*"){
  return num1 * num2;
}
if(oper == "/"){
  return num1 / num2;
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question