Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Allocate and free dynamic memory, group data structures and using arrays
- #define _CRT_SECURE_NO_DEPRECATE
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <string.h>
- #include <ctype.h>
- #define PI 3.14159265359
- typedef struct {
- double latitudes;
- double longitudes;
- } geoCoord;
- double radians(double);
- double distanceKm(geoCoord *, double *, int);
- int main(void)
- {
- int arraySize = 0;
- double totalDistance = 0;
- double distance = 0;
- geoCoord *coord;
- printf("Please enter the number of waypoints you like to enter: ");
- while (1)
- {
- if (scanf("%d", &arraySize) == 1)
- break;
- else
- while (getchar() != '\n')
- continue;
- printf("Try again (expected number >= 0): ");
- }
- getchar();
- //using malloc(memory allocation) to specify the number of bytes in memory
- coord = (geoCoord *)malloc(arraySize * sizeof(geoCoord));
- //users shall enter the place of depature and the destinations
- printf("Enter number of waypoints as \"<latitude> <longitude>\": ");
- for (int i = 0; i < arraySize; i++)
- {
- while (1)
- {
- printf("\n Waypoint %d: ", i + 1);
- //sscanf is used to read formatted input from a string/buffer
- if (scanf("%lf %lf", &coord[i].latitudes, &coord[i].longitudes) != 2)
- {
- printf("Invalid input (expected \"<latitude> <longitude>\"): ");
- }
- else
- {
- break;
- }
- while (getchar() != '\n')
- continue;
- }
- }
- getchar();
- distance = distanceKm(coord, &totalDistance, arraySize);
- printf("\nBy taking this route you will travel %.1lf Km.", distance);
- //function loop to go through and add up all the way points (can use previous lab module)
- //Clear memory
- free(coord);
- getchar();
- return 0;
- }
- double distanceKm(geoCoord *coord, double *totalDistance, int arraySize)
- {
- double deltaX, deltaY, lDistKm;
- double latA, lonA, latB, lonB;
- //for loop to compare previous coordinate to next coordinate
- //count initially set to 1 so that element 0 is compared to element 1 etc etc.
- //with each loop j increases until it is 7 but comp is always 1 ahead.
- for (int j = 0; j < arraySize - 1; j++)
- {
- latA = coord[j].latitudes;
- lonA = coord[j].longitudes;
- lonB = coord[j + 1].longitudes;
- latB = coord[j + 1].latitudes;
- //used local distance KM formula
- deltaY = 111.3 * fabs((radians(latA - latB)));
- deltaX = 111.3 * cos((radians(latA + latB)) / 2) * fabs(radians(lonA - lonB));
- lDistKm = sqrt(deltaX * deltaX + deltaY * deltaY) * (180 / PI);
- //Sets value in pointer
- *totalDistance += lDistKm;
- /*Sum check - uncomment to use*/
- // printf("|latA %lf lonA %lf| + |latB %lf lonB %lf| = %.2lf\n", latA, lonA, latB, lonB, *totalDistance);
- }
- return *totalDistance;
- }
- double radians(double rad)
- {
- return(rad * PI / 180);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement