using System; // Import the System namespace to use basic classes like Console
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
double num1, num2, result; // Declare variables for two numbers and the result
string operation; // Declare a variable to store the operation
// Ask the user for the first number
Console.Write("Enter the first number: ");
num1 = Convert.ToDouble(Console.ReadLine()); // Read and convert the input to double
// Ask the user for the operation
Console.Write("Enter operation (+, -, *, x, /): ");
operation = Console.ReadLine(); // Read the operation as a string
// Ask the user for the second number
Console.Write("Enter the second number: ");
num2 = Convert.ToDouble(Console.ReadLine()); // Read and convert the second number to double
// Perform the operation using "if"
if (operation == "+") // Check if the operation is addition
{
result = num1 + num2; // Perform addition
Console.WriteLine($"{num1} + {num2} = {result}"); // Display the result
}
else if (operation == "-") // Check if the operation is subtraction
{
result = num1 - num2; // Perform subtraction
Console.WriteLine($"{num1} - {num2} = {result}"); // Display the result
}
else if (operation == "*" || operation == "x") // Check if the operation is multiplication (consider both '*' and 'x')
{
result = num1 * num2; // Perform multiplication
Console.WriteLine($"{num1} * {num2} = {result}"); // Display the result
}
else if (operation == "/") // Check if the operation is division
{
if (num2 != 0) // Check if the divisor is not zero
{
result = num1 / num2; // Perform division
Console.WriteLine($"{num1} / {num2} = {result}"); // Display the result
}
else // If the divisor is zero
{
Console.WriteLine("Error: Cannot divide by zero."); // Display an error message
}
}
else // If the operation is not recognized
{
Console.WriteLine("Invalid operation. Please use +, -, *, x, or /."); // Display an error message
}
}
}
Salida
Case 1:
Enter the first number: 10
Enter operation (+, -, *, x, /): +
Enter the second number: 5
10 + 5 = 15
Case 2:
Enter the first number: 10
Enter operation (+, -, *, x, /): x
Enter the second number: 5
10 * 5 = 50
Case 3:
Enter the first number: 10
Enter operation (+, -, *, x, /): /
Enter the second number: 0
Error: Cannot divide by zero.
Case 4:
Enter the first number: 10
Enter operation (+, -, *, x, /): -
Enter the second number: 5
10 - 5 = 5
Case 5:
Enter the first number: 10
Enter operation (+, -, *, x, /): /
Enter the second number: 2
10 / 2 = 5
Case 6:
Enter the first number: 10
Enter operation (+, -, *, x, /): &
Enter the second number: 5
Invalid operation. Please use +, -, *, x, or /.
Código de Ejemplo Copiado!