Altitude data from a rocket flight recorder is stored in a data file named fligh
ID: 3542647 • Letter: A
Question
Altitude data from a rocket flight recorder is stored in a data file named flight.txt. The data in this file are arranged in two columns. The first column values are times listed in seconds, and the second column values are the heights in meters that correspond to these times. There is no sentinel value to indicate the end of data, nor is there a pre-number in the data file to indicate the number of records that follow. The time values are always in ascending order.
An example of a data file is shown below:
0.0 0.0
1.0 7.9
2.0 15.7
3.0 23.3
5.0 38.7
10.0 72.3
20.0 128.9
30.0 168.3
40.0 192.5
50.0 200.1
60.0 192.8
70.0 168.3
80.0 128.4
90.0 72.7
Write a program that will work with a data file that is structured like the file described above. You will not know how many data values are in the file ahead of time. (See example program 5-22 in your book or look at the course notes to see how to read from a file until the end of data is encountered).
Your program should do the following:
When the input time matches a time in the data file, the corresponding height will also be in the data file (it will be the very next data value). When the input time is between two adjacent times in the data file, your program will need to linearly interpolate the data to determine the height corresponding to the input time.
Note on linear interpolation:
If an input time t is between and in the data file, then the height h corresponding to it can be determined from the equation:
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
double time;
double time_array[100],height_array[100];
int count=0;
ifstream infile("flight.txt");
if(!infile)
{
cout << "Unable to open file so Exiting from progrma" << endl;
return 0;
}
while(!infile.eof())
{
infile >> time_array[count] >> height_array[count];
count++;
}
cout <<"Enter time :";
cin >> time;
cout << endl;
bool is_record_found = false;
for(int i=0; i<count; i++)
{
if(time_array[i] == time)
{
is_record_found = true;
cout <<"for given time :" << time << " Corresponding rocket height given by " << height_array[i] << endl;
break;
}
}
//We didnt get exact match so follow interpolation approach.
int current_index = 0;
if(!is_record_found)
{
for(int i=0; i<count; i++)
{
if(time_array[i] < time)
{
current_index = i;
}
else
break;
}
double height = height_array[current_index] + ((time-time_array[current_index])/(time_array[current_index+1]-time_array[current_index]))*
(height_array[current_index+1]-height_array[current_index]);
cout <<"for given time :" << time << " Corresponding rocket height given by " << height << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.