The miles per gallon (mpg) of a car can be calculated by dividing the miles driven by the number of gallons of gas used. Any time you have division in a computer program you have to check division by zero (the results of division by zero is infinity). If you don't a user could input zero for the number of gallons used and crash your program. You should also always check that any numeric input only accepts numbers and not letters, and that any numeric input is reasonable. For example, miles driven is probably not more than 1000 miles and is also a positive value (negative miles driven makes no sense, as does negative gallons used).
Assignment: Write a program to calculate mpg given miles driven and gallons used. Use exception handling in C# to check for numeric inputs and division by zero. Use appropriate logic to check for the reasonableness of the inputs.
using System;
namespace MathApp
{
class Program
{
static void Main()
{
int Miles = 0, Gallons = 0;
try
{
Console.WriteLine($"Enter the miles");
int.TryParse(Console.ReadLine(), out Miles);
Console.WriteLine(Miles);
if (Miles < 1 || Miles > 1000)
{
throw new IndexOutOfRangeException();
}
Console.WriteLine($"Enter the gallons");
int.TryParse(Console.ReadLine(), out Gallons);
Console.WriteLine(Gallons);
if (Gallons < 1 || Gallons > 100)
{
throw new IndexOutOfRangeException();
}
Console.WriteLine((double)Miles / Gallons);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Check the correctness of the entered data");
Main();
}
}
}
}
Comments
Leave a comment