Write a program in C that Defines 2 structured types, one for a 2D point (floati
ID: 3774243 • Letter: W
Question
Write a program in C that Defines 2 structured types, one for a 2D point (floating point coordinates named x and y ), the other for a triangle consisting of 3 points. Have main declare a triangle and then fill in its vertices with random floating point numbers between 0 and 1. Write a second function named centroid with a single input (parameter), a triangle. The purpose of the centroid function is, surprise, surprise, to compute and return the centroid of a triangle. Have main print out the vertices of the triangle and then print out the results of the call to centroid
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
struct twoDPoint //structure for x and y coordinates
{
double x;
double y;
};
struct Triangle //structure for 3 points (x,y) denoting a triangle
{
struct twoDPoint p1;
struct twoDPoint p2;
struct twoDPoint p3;
};
void centroid(float x1,float x2,float x3,float y1,float y2,float y3) //function to compute centroid of triangle
{
double CX1 = (x1+x2+x3)/3;
double CY1 = (y1+y2+y3)/3;
printf(" Centroid(X1,Y1) = (%lf,%lf)",CX1,CY1);
}
int main(void)
{
struct Triangle t;
t.p1.x = ((double) rand() / (RAND_MAX)) ; //generate random number between 0 and 1
t.p1.y = ((double) rand() / (RAND_MAX)) ;
t.p2.x = ((double) rand() / (RAND_MAX)) ;
t.p2.y = ((double) rand() / (RAND_MAX)) ;
t.p3.x = ((double) rand() / (RAND_MAX)) ;
t.p3.y = ((double) rand() / (RAND_MAX)) ;
printf("x1= %lf y1=%lf x2=%lf y2=%lf x3=%lf y3=%lf",t.p1.x,t.p1.y,t.p2.x,t.p2.y,t.p3.x,t.p3.y);
centroid(t.p1.x,t.p1.y,t.p2.x,t.p2.y,t.p3.x,t.p3.y);
return 0;
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.