How to modify this program so it can read x and fx from an input file? //header
ID: 3631294 • Letter: H
Question
How to modify this program so it can read x and fx from an input file?
//header files
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
char ch;
const int SIZE=24;
//x-values initialization
float x[SIZE]={1.1234,2.2468,3.3702,4.4936,
5.617,6.6704,7.8638,8.987,10.110,
11.234,12.357,13.480,14.604,15.727,
16.851,17.974,19.097,20.221,22.468,
23.59,24.7148,25.8382,26.961,28.085};
//corresponding funtion vlaues
float fx[SIZE]={
167.5600,137.6441,110.2526,85.384,
63.040,43.220,25.925,11.53,-1.093,
-10.81726,-18.0166,-22.692,-24.480,
-21.573,-16.152,-8.208008,2.260,15.253,
30.771,48.812,69.377,92.466,118.07,146.21
};
int i;
float n,temp1,temp2,res;
do{
do{
cout<<"Enter x-value "< cin>>n;
}while(n<1 ||n>28.085);
for(i=0;i<24;i++)
{
if(n==x[i])
{
cout<<"f(x)"< system("pause");
}
else if(n>x[i])
break;
}
temp1=x[i-1];
temp2=x[i+1];
//formula for linear interpolation
float mid=(temp1-temp2)/(x[i-1]-x[i+1]);
res=temp2+mid*(x[i-1]-x[i+1]);
cout< cout<<"do y want to continue(y/n)";cin>>ch;
}while(ch=='y');
system("pause");
return 0;
}
Explanation / Answer
please rate - thanks
in response to your comment
x and fx are 2 columns as in the picture
#include<iostream>
#include <fstream>
#include<iomanip>
using namespace std;
int main()
{
char ch;
const int SIZE=24;
float x[SIZE];
float fx[SIZE];
char filename[30];
int i,j;
cout<<"Enter filename: ";
cin>>filename;
ifstream in;
in.open(filename); //open file
if(in.fail()) //is it ok?
{ cout<<"file did not open please check it ";
system("pause");
system("exit");
}
for(i=0;i<SIZE;i++)
{in>>x[i];
in>>fx[i];
}
in.close();
float n,temp1,temp2,res;
//if this is supposed to be reading x and fx get rid of it. I really don't understand what you are trying to do
do{
do{
cout<<"Enter x-value "< cin>>n;
}while(n<1 ||n>28.085);
for(i=0;i<24;i++)
{
if(n==x[i])
{
cout<<"f(x)"; system("pause");
}
else if(n>x[i])
break;
}
temp1=x[i-1];
temp2=x[i+1];
//formula for linear interpolation
float mid=(temp1-temp2)/(x[i-1]-x[i+1]);
res=temp2+mid*(x[i-1]-x[i+1]);
cout< cout<<"do y want to continue(y/n)";cin>>ch;
}while(ch=='y');
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.