+ 1

How to make a c programm using for loop that input 2D points and show the farthest point from the origin?

int main() { int n,i,x,y; float d,m; d=0; m=0; printf("How many 2D points="); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&x); scanf("%d",&y);} for(i=0;i<n;i++){ d=sqrt(x*x+y*y); if(d>m){ d=m; } } } printf("\n%d",&x); printf("\n%d",&y); is this logic okay return 0; }

28th Nov 2020, 12:33 AM
Nisha
1 Respuesta
+ 1
This would work: #include <stdio.h> #include <math.h> int main() { int n,i,x,y, maxDistanceX, maxDistanceY; float d,m; d=0; m=0; printf("How many 2D points="); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&x); scanf("%d",&y); d=sqrt(x*x+y*y); if(d>m){ m=d; maxDistanceX = x; maxDistanceY = y; } } printf("\n%d",maxDistanceX); printf("\n%d",maxDistanceY); return 0; } Specific changes are explained below: 1. Your check for d > m was on the right track but you need to store m = d instead of d = m because d is overwritten every iteration of your loop. 2. You need to merge your loops because your values for x and y are replaced in each iteration. There is no way for the second loop to access each and every point scanned in with the first loop. Using an array is another way to fix this but maybe you're not far enough into learning c to use arrays. 3. You need to store the coordinates of x and y when you find a larger distance. Your original code will print the last point every time regardless of how far from origin it is in relation to the other read in points. My changes store the most distant point in maxDistanceX and maxDistanceY to fix this problem. 4. When using printf to print an int, the & should not be used. You need & for scanf but not printf in this situation.
23rd Dec 2020, 3:54 PM
Josh Greig
Josh Greig - avatar