Grupo
Conceptos básicos control de flujo en C#
Objectivo
Escriba un programa en C# que solicite al usuario dos números y muestre su división. Los errores se deben detectar con "try..catch".
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
class Program
{
static void Main()
{
// Prompt the user for the first number (dividend)
Console.Write("Enter the first number: ");
double num1 = Convert.ToDouble(Console.ReadLine()); // Convert input to double
// Prompt the user for the second number (divisor)
Console.Write("Enter the second number: ");
double num2 = Convert.ToDouble(Console.ReadLine()); // Convert input to double
try
{
// Attempt to perform the division
double result = num1 / num2;
Console.WriteLine($"The result of {num1} / {num2} is: {result}"); // Output the result
}
catch (DivideByZeroException ex)
{
// Catch division by zero errors
Console.WriteLine("Error: Cannot divide by zero.");
}
catch (FormatException ex)
{
// Catch errors in case of invalid input (not numbers)
Console.WriteLine("Error: Invalid input. Please enter valid numbers.");
}
catch (Exception ex)
{
// Catch any other general exceptions
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}
Output
//Example 1 (Valid Division):
Enter the first number: 10
Enter the second number: 2
The result of 10 / 2 is: 5
//Example 2 (Division by Zero):
Enter the first number: 10
Enter the second number: 0
Error: Cannot divide by zero.
//Example 3 (Invalid Input - Non-numeric):
Enter the first number: 10
Enter the second number: abc
Error: Invalid input. Please enter valid numbers.
//Example 4 (General Error):
Enter the first number: 10
Enter the second number: 5
Error: An unexpected error occurred: Not defined
Código de ejemplo copiado
Comparte este ejercicio de C#