Write a C# program that prompts the user to input two numbers and divides them. Handle an exception when the user enters non-numeric values.
using System; public class Program { public static void Main(string[] args) { // Prompt the user to input two numbers. Console.Write("Enter the first number: "); string firstNumberInput = Console.ReadLine(); Console.Write("Enter the second number: "); string secondNumberInput = Console.ReadLine(); // Try to convert the input strings to doubles. double firstNumber; double secondNumber; try { firstNumber = Convert.ToDouble(firstNumberInput); secondNumber = Convert.ToDouble(secondNumberInput); } catch (FormatException) { // Handle the exception when the user enters non-numeric values. Console.WriteLine("Invalid input. Please enter two numbers."); return; } // Divide the two numbers and display the result. double result = firstNumber / secondNumber; Console.WriteLine("The result of dividing {0} by {1} is {2}.", firstNumber, secondNumber, result); } }
Write a C# program that prompts the user to input two numbers and divides them. Handle an exception when the user enters non-numeric values.
Reviewed by Bhaumik Patel
on
9:57 PM
Rating: