In: Computer Science
Create a program that reads a file of 2D coordinates and calculates the bounding box and center of the bounding box. The bounding box is defined as the minimum area that fully encompasses all the coordinates. The center of that bounding box is calculated by taking the mean of the bounding box coordinates: ( x1+x2 2 , y1+y2 2 ). • If the input file cannot be opened, warn the user by printing "CANNOT OPEN FILE." to stdout. • Print the resulting bounding box and center to stdout using the format string %.2f,%.2f,%.2f,%.2f,%.2f,%.2f, following the pattern xmin, ymin, xmax, ymax, xcenter, ycenter. • Save your code as prob2.c.
Example Run
$ ./a.out keypoints.txt
0.00,0.00,100.00,100.00,50.00,50.00
CODE -
#include<stdio.h>
int main(int argc, char** argv)
{
// Open file using file name passed as command line argument
FILE* infile = fopen(argv[1], "r");
// Display error message if file can't be opened.
if(!infile)
printf("\nCANNOT OPEN FILE.\n");
else
{
float x, y, xmin = 99999, ymin = 99999, xmax = -99999, ymax = -99999, xcenter, ycenter;
// Read file till end of file is reached
while(!feof(infile))
{
// Read x and y coordinate seperated by space in the file
fscanf(infile, "%f %f", &x, &y);
// Determine the coordinates of bounding box
if (x < xmin)
xmin = x;
if(y < ymin)
ymin = y;
if (x > xmax)
xmax = x;
if(y > ymax)
ymax = y;
}
// Determine the center coordinates of bounding box
xcenter = (xmin + xmax) / 2;
ycenter = (ymin + ymax) / 2;
// Display the coordinates of bounding box and coordinates of its center
printf("%.2f,%.2f,%.2f,%.2f,%.2f,%.2f", xmin, ymin, xmax, ymax, xcenter, ycenter);
}
return 0;
}
SCREENSHOTS -
INPUT TEXT FILE -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.