C++ code to calculate distance formula -Read in a file (\"input.txt\") which con
ID: 663397 • Letter: C
Question
C++ code to calculate distance formula
-Read in a file ("input.txt") which consists of an array:
1 2 3 4 5 6
7 8 9 0 1 2
9 8 7 1 2 3
11 12 13 14 15 16
99 99 99 99 99 99
- fin >> x; // reads in data from input.txt to the variable x
- fout << x; // writes out data from the variable xto output.txt
- the first line reads in one number from the input.txt file and saves it to x. the second line writes the value of x to output.txt.
- You can stream in or out several variables at the same time:
fin >> x >> y >> z >>;
fout << x;
- Write a function called calcDistance(). takes 6 parameters (all doubles which corresponds to two x, two y, and two z coordinates) calculate distance between the two points and return that calculation to the main() function as a double.
- use the built in sqrt() function ( double sqrt (double x); )
- double pow (double x, double y); // corresponds to xy
- read in each of the first X coordinates in one array. the Y coordinates in one array, and the Z coordinate in another. Might have to do this twice to storethe two sets of points.
- Arrays for this should be no more than 20 distances to calculate: double variableName[20];
**Output should be**
5.19615
12.1244
10.7703
5.19615
0
Explanation / Answer
#include <iostream>
#include <math.h>
#include <fstream.h>
#include <vector.h>
using namespace std;
double calcDistance(float[],float[],float[]);
int main()
{
std::ifstream file("input.txt");
std::string str;
ofstream fout;
while (std::getline(file, str))
{
vector<string> sep = split(str, ',');
float x[2]={sep[0],sep[1]};
float y[2]={sep[2],sep[3]};
float z[2]={sep[4],sep[5]};
double res;
res=calcDistance(x,y,z);
fout.open("output.txt");
fout<<res<<endl;
}
fout.close();
return 0;
}
double calcDistance(float x[2],float y[2],float z[2])
{
double dist=pow(x[1]-x[0],2.0)+pow(y[1]-y[0],2.0)+pow(z[1]-z[0],2.0);
double myDistance=sqrt(dist);
return myDistance;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.