Reading\Writing a function from a file
Basically, what i am trying to do, is write a program that will integrate a function using the rectangle method.
I'm fine with the maths part.
And i can declare a function within the actual file. What i would love to do, in the end is to be able to run the program, be able to input any function (of x - say x^2, or x^3 - 3x for example), and then integrate this by the chosen method.
At the minute, i can only change the function within the cpp pile, and not within the program.
Any suggestions would be great. I am a fairly newcomer to C++ so sorry if i don't grasp what is needed!!
I thought maybe i could get the program to first ask u to input the function, and save that in a seperate file, and then later on it can call on that saved file and read from it the function thats been inputted.
Anyway, here is what i have:
Code:
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <fstream.h>
float funcj(float);
float main()
{
int n, i;
float a, b, h, x, s, integral;
i = 0;
cout << "Please input a, the lower bound: ";
cin >> a;
cout << "\nPlease input b, the upper bound: ";
cin >> b;
if (a >= b)
{
cout << "\nYou have inputted the data incorrectly. Please try again.\n";
}
else {
integral = 0;
cout << "\nPlease input the number of strips required: ";
cin >> n;
{
h = fabs(a - b) / n;
while ( i < n)
{
x = a + i * h;
s = h * funcj(x);
integral = integral + s;
i++;
}
cout <<"\nThe answer is: " << integral;
}
}
}
float funcj(float x)
{
float f;
f = (x*x) - (5*x) - 3 ;
return f;
}