通过使用大圆距离公式查找附近出租车的 C++ 程序
在本文中,我们讨论一个程序,该程序使用大圆距离公式查找附近的出租车(小于 50 公里)。
假设我们得到一个 JSON 文件,其中包含需要出租车的乘客的姓名和坐标,以及所有可用的出租车的坐标。
为了解决此问题,我们将 GPS 坐标转换为 double。在 double 形式中,我们将最终将它们以角度形式转换为弧度。然后,我们可以最终应用大圆距离公式来查找距用户位置 50 公里以内的出租车。
请注意,由于输入数据量大,我们将 JSON 文件作为程序中的输入,并同时在另一个 JSON 文件中输出结果。
示例
#include <bits/stdc++.h>
using namespace std;
#define pi 3.14159265358979323
#define earth_radius 6371.0
//defining the user's coordinates
#define latitude1d 12.9611159
#define longitude1d 77.6362214
ifstream users ("input.access_file");
ofstream out ("output.access_file");
//converting degree to radian
double to_radian(double degree) {
return ( degree * (pi/180));
}
//to calculate the distance
double cal_distance(double latitude2d, double longitude2d) {
double lat1, lon1, lat2, lon2, diff_lon, great_circle;
lat1 = to_radian(latitude1d);
lon1 = to_radian(longitude1d);
lat2 = to_radian(latitude2d);
lon2 = to_radian(longitude2d);
diff_lon = lon2 - lon1;
great_circle = acos( sin(lat1) * sin(lat2) + cos(lat1) *cos(lat2) * cos(diff_lon) );
return (earth_radius * great_circle);
}
//creating structure to access JSON file
struct access_file {
long long int user_length, i, j, x, y, m, n, f, friends,id[100000];
char latitude_string[1000], longitude_string[1000], id_string[1000], name[1000];
double latitude2d, longitude2d;
string line;
//to check the value of distance
void check_distance() {
if (cal_distance(latitude2d, longitude2d) <=50.0000) {
id[i] = atoll(id_string);
i++;
out << "{\"User_id\": " << id[i - 1] << ", \"Name\": " << name << "}" << endl;
}
}
void file_parser() {
if (users.is_open()) {
while (getline(users, line)) {
f = 0; x = 0; y = 0; friends = 0; m = 0, n = 0;
user_length = line.size();
for (j = 0; j < user_length; j++) {
if (line[j] == '"')
f++;
else if (line[j] == ':')
friends++;
if (f == 3) {
j++;
while (line[j] != '"') {
latitude_string[x] = line[j];
x++; j++;
}
j--; latitude_string[x] = '\0';
}
else if (f == 13) {
j++;
while (line[j] != '"') {
longitude_string[y] = line[j];
y++; j++;
}
j--; longitude_string[y] = '\0';
}
if (friends == 2) {
j += 2;
while (line[j] != ',') {
id_string[m] = line[j];
m++; j++;
}
j--; id_string[m] = '\0';
friends++;
}
else if (friends == 4) {
j += 2;
while (line[j] != ',') {
name[n] = line[j];
n++; j++;
}
j--; name[n] = '\0';
friends++; f += 2;
}
}
//converting string to float
latitude2d = atof(latitude_string);
longitude2d = atof(longitude_string);
check_distance();
}
}
//closing input file
users.close();
//closing output file
out.close();
}
};
int main() {
access_file object;
object.file_parser();
return 0;
}输出
(A file named output.json will be created at the same place where the code and the input.json file is stored.)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP