Please complete the following guidelines and hints. Using C language. Please use this template:
Please complete the following guidelines and hints. Using C language.
Please use this template:
#include <stdio.h>
#define MAX 100
struct cg { // structure to hold x and y coordinates and mass
float x, y, mass;
}masses[MAX];
int readin(void)
{
/* Write this function to read in the data
into the array masses
note that this function should return the number of
masses read in from the file */
}
void computecg(int n_masses)
{
/* Write this function to compute the C of G
and print the result */
}
int main(void)
{
int number;
if((number = readin()) > 0)
computecg(number);
return 0;
}
Testing your work
Typical Input from keyboard:
4
0 0 1
0 1 1
1 0 1
1 1 1
Typical Output to screen:
CoG coordinates are: x = 0.50 y = 0.50
Here is the solution for above problem:
cog.c
#include <stdio.h>
#define MAX 100
struct cg { // structure to hold x and y coordinates and mass
float x, y, mass;
}masses[MAX];
/* Write this function to read in the data
into the array masses
note that this function should return the number of
masses read in from the file */
int readin(void)
{
int n,i;
/*reading number of masses*/
printf("Enter number of masses: ");
scanf("%d",&n);
/*loop to read array n number of x,y and mass*/
for(i=0;i<n;i++)
{
printf("Enter x, y and mass: ");
scanf("%f %f %f",&masses[i].x,&masses[i].y,&masses[i].mass);
}
/*returning number of masses read*/
return n;
}
/*Write this function to compute the C of G
and print the result */
void computecg(int n_masses)
{
float sum_x=0, sum_y=0, sum_mass=0, cg_x, cg_y;
int i;
/* loop to compute sum of x_mass, sum of y_mass, sum of mass*/
for(i=0; i<n_masses; i++)
{
/*computing sum of x_mass*/
sum_x=sum_x + (masses[i].x * masses[i].mass);
/*computing sum_of y_mass*/
sum_y=sum_y + (masses[i].y * masses[i].mass);
/*computing sum of masses */
sum_mass=sum_mass+ (masses[i].mass);
}
/*computing CoG x and CoG y*/
cg_x = sum_x/sum_mass;
cg_y = sum_y/sum_mass;
printf("CoG coordinates are: x= %.2f y=%.2f ",cg_x,cg_y);
}
/*Main function*/
int main(void)
{
int number;
if((number = readin()) > 0)
computecg(number);
return 0;
}
Step by step
Solved in 2 steps with 1 images