Answer to Question #315276 in C# for Dave

Question #315276

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. 


1
Expert's answer
2022-03-21T12:35:37-0400
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();
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS