need help with while loop problem

Feb 13, 2017 at 2:37am
I am trying to create a program where i would be able to calculate center of mass in 2-D. Everything has been working out fine with the code except it is giving me the wrong answers and placing the same thing in both the x and y outputs i have set. My obvious guess was that there was a math problem but i honestly do not know how to go about fixing this. Can someone please tell me how to fix this problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <stdio.h>
 #include <math.h>
void main() {
	int num_terms = 0;
	double COM_x = 0.0;
	double COM_y = 0.0;
	double y_value;
	double x_value;
	double mass_value;

	printf("How many particles are in the system?:");
	scanf("%i", &num_terms);
	int count = 1;
	while (count <= num_terms) {
		printf("Enter particle information %i in the format x y mass: ", count);
		scanf(" %lf", &x_value);
		scanf(" %lf", &y_value);
		scanf(" %lf", &mass_value);
		count++;
		COM_x = COM_x + (x_value * mass_value) / x_value;
		COM_y = COM_y + (y_value * mass_value) / y_value;
	}
	printf("\n");
	printf("Center of mass is located at: %lf, ", COM_x);
	printf("%lf", COM_y);
	printf("\n");	
}
Feb 13, 2017 at 6:02am
You have a maths problem.

Centre of mass is
sum( x_value * mass_value ) / sum( mass_value)
and similarly in the y direction.

Do the relevant sums in the loop. Do the division by total mass after the loop has ended.
Feb 14, 2017 at 2:45pm
Thank you, i finally got it working properly.
Topic archived. No new replies allowed.