Home > front end >  How can i simplify my code about finding the area of rectangle? [closed]
How can i simplify my code about finding the area of rectangle? [closed]

Time:10-06

finding the area of a rectangle using the coordinates of the diagonals

            Console.Write("enter x1: ");
        string coordx1 = Console.ReadLine();
        double x1 = Convert.ToInt32(coordx1);
        Console.Write("enter y1: ");                  
        string coordy1 = Console.ReadLine();
        double y1 = Convert.ToInt32(coordy1);

        Console.Write("enter x2: ");
        string coordx2 = Console.ReadLine();
        double x2 = Convert.ToInt32(coordx2);
        Console.Write("enter y2: ");                  
        string coordy2 = Console.ReadLine();
        double y2 = Convert.ToInt32(coordy2);

        double S = (x2 - x1) * (y2 - y1);             
        Console.WriteLine("S = "   S);

CodePudding user response:

There isn't really anything that you can do to simplify the code - you have to prompt and then compute. You do have one possible flaw though - you only read the coordinates as int even though you are storing in a double. If that works for you, then fine... but if you need to be able to enter numbers with decimal points, then you should use:

double x1 = Convert.ToDouble(coordx1);
// repeat for the other 3 values

Also, depending on how the user enters the points, you may end up with negative values so you can prevent that with:

double S = Math.Abs(x2 - x1) * Math.Abs(y2 - y1);        

CodePudding user response:

Already your code is simple and easy to read, if you want reduce size of your code and want to give user a way to provide all co-ordinates in a single line then try below,

Console.WriteLine("Enter co-ordinates in a given sequence(x1 y1 x2 y2)");
var inputs = Array.ConvertAll(Console.ReadLine().Trim().Split(), double.Parse);
if(inputs.Length == 4)
{
   var area = (inputs[2] - inputs[0]) * (inputs[3] - inputs[1]);
   Console.WriteLine($"Area of Rectangle is = {area}");
}
else
   Console.WriteLine("Incorrect values passed");

CodePudding user response:

There is not really anything wrong with your code, but you can make it a bit more readable and concise and reduce code repetition by using a method

double x1 = GetInput("x1");
double y1 = GetInput("y1");
double x2 = GetInput("x2");
double y2 = GetInput("y2");

double area = (x2 - x1) * (y2 - y1);             
Console.WriteLine($"Area = {area}");


private double GetInput(string name)
{
    Console.Write($"Enter {name}: ");
    return Convert.ToDouble(coordx1);
}

Ideally you should expand the GetInput method to do validation of the input.

  • Related