Here's a simple console-based calculator written in C#. You can use this code as a starting point and modify it to add more features or improve the user interface.
using System;
namespace CmdCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Command Line Calculator!");
while (true)
{
Console.WriteLine("Enter first number:");
string input1 = Console.ReadLine();
Console.WriteLine("Enter second number:");
string input2 = Console.ReadLine();
Console.WriteLine("Enter an operation (+, -, *, /):");
string operation = Console.ReadLine();
double num1, num2;
bool isNum1Valid = double.TryParse(input1, out num1);
bool isNum2Valid = double.TryParse(input2, out num2);
if (!isNum1Valid || !isNum2Valid)
{
Console.WriteLine("Invalid input. Please enter valid numbers.");
continue;
}
double result;
bool isOperationValid = operation == "+" || operation == "-" || operation == "*" || operation == "/";
if (isOperationValid)
{
switch (operation)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero.");
continue;
}
result = num1 / num2;
break;
default:
Console.WriteLine("Invalid operation.");
continue;
}
Console.WriteLine($"Result: {result}");
}
else
{
Console.WriteLine("Invalid operation.");
}
Console.WriteLine("Do you want to continue? (y/n)");
string continueInput = Console.ReadLine();
if (continueInput.ToLower() != "y")
{
break;
}
}
Console.WriteLine("Thank you for using the Command Line Calculator. Goodbye!");
}
}
}
To run this code, create a new Console App project in Visual Studio, replace the generated code with the provided code, and press F5 to run the application.