This is the wording of the exercise.
**Create a console application that asks the user for two numbers in the range 0-255 and then divides the first number by the second:
Enter a number between 0 and 255: 100
Enter another number between 0 and 255: 8
100 divided by 8 is 12
Write exception handlers to catch any thrown errors:
Enter a number between 0 and 255: apples
Enter another number between 0 and 255: bananas
FormatException: Input string was not in a correct format.**
This is the program I wrote, it works. But my intention was to make it shorter by writing byte result = divisor / dividend;
Both divisor and dividend were already casted as a byte, so why can't I use them directly in the code?
I had to calculate the operation using an int and then cast that int into a byte. (2 steps instead of one, which is puzzling me)
Am I missing something?
static void Main(string[] args)
{
checked
{
try
{
WriteLine("Enter a number between 0 and 255");
string firstNumber = ReadLine();
byte divisor = Convert.ToByte(firstNumber);
WriteLine("Enter another between 0 and 255");
string secondNumber = ReadLine();
byte dividend = Convert.ToByte(secondNumber);
int calculation = divisor / dividend;
byte result = Convert.ToByte(calculation);
WriteLine($"The result of the division between {divisor} and {dividend} is {result}");
}
catch (OverflowException)
{
WriteLine("The number you entered is either lower than 0 or superior to 255, please enter a number between 0 and 255");
}
catch (FormatException)
{
WriteLine("You didn't enter a number");
}
catch (Exception ex)
{
WriteLine($"{ex.GetType()} says {ex.Message}");
}
}
ReadKey();
}