Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace testcalc
- {
- public class Program
- {
- delegate double MathAction(double a, double b);
- static void Main() {
- MathAction action;
- double a = 0, b = 0, result = 0;
- do {
- Console.Clear();
- Console.WriteLine("CALC");
- Console.WriteLine("Введите первое число, потом знак, потом второе число.\nВведите exit для выхода");
- if (!GetNumber(out a))
- continue;
- string actionText = Console.ReadLine();
- if (!GetNumber(out b))
- continue;
- try {
- switch (actionText) {
- case "+":
- action = (double x, double y) => {
- return a + b;
- };
- break;
- case "-":
- action = (double x, double y) => {
- return a - b;
- };
- break;
- case "/":
- action = (double x, double y) => {
- if (y == 0)
- throw new DivideByZeroException("ERROR: деление на ноль!");
- return x / y;
- };
- break;
- case "*":
- action = (double x, double y) => {
- return a * b;
- };
- break;
- case "%":
- action = (double x, double y) => {
- if (y == 0)
- throw new DivideByZeroException("ERROR: деление на ноль!");
- return x % y;
- };
- break;
- default:
- throw new ArgumentException("ERROR: неподдерживаемый оператор!");
- }
- }
- catch (ArgumentException ex) {
- Console.WriteLine(ex.Message);
- continue;
- }
- try {
- result = action(a, b);
- }
- catch (DivideByZeroException ex) {
- Console.WriteLine(ex.Message);
- continue;
- }
- Console.WriteLine("Результат: {0}", result);
- } while (Console.ReadLine() != "exit");
- }
- static bool GetNumber(out double a) {
- if (!double.TryParse(Console.ReadLine(), out a)) {
- Console.WriteLine("ERROR: Ошибка ввода!");
- return false;
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement