Question
(Central city) Given a set of cities, the central point is the city that has the shortest total distance to all other cities. Write a
(Central city)
Given a set of cities, the central point is the city that has the shortest total distance to all other cities. Write a program that prompts the user to enter the number of cities and the locations of the cities (coordinates), and finds the central city and its total distance to all other cities. Assume that the maximum number of cities is 20.
Sample Run
Enter the number of cities: 5
Enter the coordinates of the cities: 2.5 5 5.1 3 1 9 5.4 54 5.5 2.1
The central city is at (2.5, 5.0)
The total distance to all other cities is 60.81
I'm stuck. I need the user to input some data but I cant have a variable in the array so I can't make it constant. Here's what I have so far:
Thanks in advance
#include
int main() { int n = 1, i, j; double dis;
cout << "Enter the number of cities: "; cin >> n; double coordinates[n][2], temp1, temp2; double distance[n]; for (int i = 0; i < 2; i++) {//loop for traveling the column of the array for (int j = 0; j < n; j++) { cin >> coordinates[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { temp1 = coordinates[i][0] - coordinates[i][0]; temp2 = coordinates[i][1] - coordinates[i][1]; temp1 = temp1 * temp1; temp2 = temp2 * temp2; //measure distance dis = sqrt(temp1 + temp2); distance[i] = dis + distance[i]; } } } int pos = 0; double shortest = distance[i]; //Find closest city for (int i = 1; i < n; i++) { if (distance[i] < shortest) { shortest = distance[i]; pos = i; } } //Location of city cout << "The central city is at: " << "(" << coordinates[pos][0] << "," << coordinates[pos][1] << ")" << endl; cout << "The total distance to all other cities is " << distance[pos] << " "; return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started