Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Pls Help With This C Program

+1 vote
asked May 6, 2020 by reda cocelli (200 points)

For points P(x1,y1,z1) and Q(x2,y2,z2) in 3-dimensional space, the Euclidean distance between them is square-root((x2−x1)2+(y2−y1)2+(z2−z1)2)

Write a struct named point in c which has values x(float), y(float) and z(float) which will represent the x, y and z coordinates of a point in 3 dimensional space. Then ask the user to enter the total number of points to be entered. If the number of points to be entered is an odd number, calculate the Euclidean distance of each point from the origin (0,0,0) and show the closest point to origin. Else, show the farthest point.

1 Answer

0 votes
answered May 8, 2020 by Hunter (520 points)

This seems to do the trick:



#include <stdio.h>
#include <math.h>

typedef struct Point {
    float x;
    float y; 
    float z;
} Point;

double findDistanceFromOrigin(Point p) {
    double x = p.x;
    double y = p.y;
    double z = p.z;
    //square-root((x2−x1)2+(y2−y1)2+(z2−z1)2)
    double distance = sqrt(pow(x, 2.0) + pow(y, 2.0) + pow(z, 2.0));
    
    return distance;
    
}

int main()
{
    int numberOfPoints;
    printf("Enter number of points:");
    scanf ("%d", &numberOfPoints);
    Point points[numberOfPoints];
    Point closest;
    Point farthest;
    for (int i = 0; i < numberOfPoints; i++) {
        printf("Enter x-coordinate for point %d:", i);
        scanf("%f",&points[i].x);
        printf("Enter y-coordinate for point %d:", i);
        scanf("%f", &points[i].y);
        printf("Enter z-coordinate for point %d:", i);
        scanf("%f", &points[i].z);
        if (i == 0) {
            closest = points[i];
            farthest = points[i];
        } else {
            if (findDistanceFromOrigin(points[i]) < findDistanceFromOrigin(closest)) {
                closest = points[i];
            }
            if (findDistanceFromOrigin(points[i]) > findDistanceFromOrigin(farthest)) {
                farthest = points[i];
            }
        }
    }
    
    if (numberOfPoints % 2) {
        printf("The closest point is located at: (%f, %f, %f)\n", closest.x, closest.y, closest.z);
    } else {
        printf("The farthest point is located at: (%f, %f, %f)\n", farthest.x, farthest.y, farthest.z);
    }
    
    return 0;
}

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...