gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
make me simple aritmetchic calculator in c#
- User
make me simple aritmetchic calculator in c#
- Assistant
Creating a simple arithmetic calculator in C# is a great way to practice your programming skills. Below is a basic example of a console application that allows the user to perform addition, subtraction, multiplication, and division operations:
using System; namespace SimpleArithmeticCalculator { class Program { static void Main(string[] args) { char continueCalculator; do { Console.WriteLine("Simple Arithmetic Calculator\n"); double num1, num2; char operation; // Input first number Console.Write("Enter the first number: "); while (!double.TryParse(Console.ReadLine(), out num1)) { Console.Write("Invalid input. Please enter a numeric value for the first number: "); } // Input operator Console.Write("Enter an operator (+, -, *, /): "); while (!char.TryParse(Console.ReadLine(), out operation) || !"+-*/".Contains(operation)) { Console.Write("Invalid operator. Please enter one of the following operators (+, -, *, /): "); } // Input second number Console.Write("Enter the second number: "); while (!double.TryParse(Console.ReadLine(), out num2)) { Console.Write("Invalid input. Please enter a numeric value for the second number: "); } // Perform calculation and display result double result = 0; bool validOperation = true; switch (operation) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 != 0) { result = num1 / num2; } else { Console.WriteLine("Error: Division by zero is not allowed."); validOperation = false; } break; default: validOperation = false; break; } if (validOperation) { Console.WriteLine($"\nResult: {num1} {operation} {num2} = {result}\n"); } // Ask user if they want to perform another calculation Console.Write("Do you want to perform another calculation? (y/n): "); continueCalculator = Console.ReadKey().KeyChar; Console.WriteLine("\n"); } while (continueCalculator == 'y' || continueCalculator == 'Y'); Console.WriteLine("Thank you for using the calculator. Goodbye!"); } } }Steps to Run the Program:
- Open Visual Studio or any other C# IDE you prefer.
- Create a new Console Application project.
- Replace the content of
Program.cswith the code above. - Run the program.
This program will prompt the user to enter two numbers and an arithmetic operator. It then performs the chosen operation and displays the result. The program will continue to offer calculations until the user decides to exit by entering 'n'.
Notes:
- Input Validation: The program includes basic input validation to ensure that the values entered for numbers are numeric and that the operator is one of
+,-,*, or/. - Error Handling: It handles division by zero by checking if
num2is zero before performing division.
Feel free to expand upon this example to add more features or refine the functionality!