-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.cs
77 lines (69 loc) · 2.21 KB
/
calculator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
class Calculator
{
// Method to perform calculations
static double Calculate(double num1, double num2, string operation)
{
switch (operation)
{
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
if (num2 != 0)
{
return num1 / num2;
}
else
{
throw new DivideByZeroException("Error: Division by zero");
}
default:
throw new InvalidOperationException("Error: Unsupported operation");
}
}
static void Main(string[] args)
{
Console.WriteLine("Simple Calculator");
while (true)
{
try
{
Console.Write("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter operation (+, -, *, /): ");
string operation = Console.ReadLine();
Console.Write("Enter second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
double result = Calculate(num1, num2, operation);
Console.WriteLine($"Result: {result}");
Console.Write("Do you want to perform another calculation? (yes/no): ");
string continueCalc = Console.ReadLine();
if (continueCalc.ToLower() != "yes")
{
break;
}
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter numeric values.");
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
}
Console.WriteLine("Goodbye!");
}
}