### Make false position method as a function.

Hello there!

At this moment, I am writing a program that solves the real root of the function f(x) = .05x - sin(x) using false position method. I have my code below . It works fine, but i want to make this false position method a function so that my main program will appear short.

I still have 5 methods left and i think that if this method is fixed then all the other remaining methods will also be fixed by similar way.

This is what i want to do in my main program:

 1234567891011121314151617 int main() { int selection; cout << "What method do you want to use?" << endl; cout << "Press 4 for false position. "<< endl; cin >> selection; if(selection == 4) { flaseposition(); }

Here is my code:

 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 #include #include #include using namespace std; double f(double); double falsi(double, double); const int MAX = 1000; int main() { double guess1, guess2; double xnew[MAX], xplus[MAX], xminus[MAX]; int imax; cout << endl; cout << "Enter first guess: "; cin >> xplus[0]; cout << endl; cout << "Enter second guess: "; cin >> xminus[0]; cout << endl; cout << "Set maximum number of iterations: "; cin >> imax; for(int i = 0; i < imax; i++) { xnew[i] = falsi(xplus[i], xminus[i]); if(f(xnew[i])> 0) { xplus[i+1] = xnew[i]; xminus[i+1]=xminus[i]; } else { xminus[i+1] = xnew[i]; xplus[i+1]=xplus[i]; } } cout << endl << endl; for(int i = 0; i < imax; i++) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(20); cout << xnew[i] << endl; } cout << endl << endl << endl; cout << "The root is approximately: "; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(20); cout << endl << endl << xnew[imax - 1]; cin.get(); cin.get(); return 0; } double f(double x) { return .05 * x - sin(x); } double falsi(double xp, double xm) { return xp - f(xp) *(xp - xm)/(f(xp) -f(xm)); }

Last edited on
First of all, it should be
if(selection == 4)
(two equals signs instead of one), since one equal sign is assignment.

Technically, you could take your current code above and pretty much rename main to falseposition (wait, did you want falseposition or flaseposition? You have the latter in your code).
Then stick your current work-in-progress main function in and you should be fine.

You might want to consider returning the calculated value from the function and move the code that prints it to the screen into main, though. (That way, you won't have to duplicate that part of the code in each of your different functions.)
Topic archived. No new replies allowed.