Code: using namespace std; # include <iostream> # include <string> # include <iomanip> # include <vector> double a; double b; double h; double f(double x) { return x* - 1; } double sign(double x) { if (x < 0) { return 0; } else { return 1; } } double FindRoot (double a,double b,double h) { double s; double x; s=sign(f(a)); while (s = sign(f(x))) { for (x=0; x < b; x=(a+b)/h) return x; } } double root=FindRoot (a, b, h); void PrintResults ( double a, double b, double root) { cout << "A root of the function f(x)=x^2-1 between " << a << " and " << b << " is " << root << endl << flush; } int main( ) { PrintResults (-2,0,0.01); return 0; } I'm unsure why nothing's being printed. I'm guessing something's wrong with the format of PrintResults or my formula for finding the root is incorrect. Help wanted urgently. Thank you.
Found the error Change : Code: double root=FindRoot (a, b, h); to Code: double root; First, you are trying to initialize a global var root outside any procedure. Second, the vars that you pass as args : a, b, h to FindRoot are un-initialized ! Change the code and it should print.
Place this line Code: double root=FindRoot (a, b, h); inside your PrintResults() function, or initialize 'root' variable inside main().
another error is this no need for for command just put return 0; its the same! No command is executed after a return!!! and of course as davidk and SaswatPadhi said change your code like this Code: using namespace std; # include <iostream> # include <string> # include <iomanip> # include <vector> [COLOR=Red]//[/COLOR]double a; [COLOR=Red]//[/COLOR]double b; [COLOR=Red]//[/COLOR]double h; ....... int main( ) { [COLOR=Red]double a=-2,b=0,h=0.01;[/COLOR] [COLOR=Red]double root=FindRoot (a, b, h); PrintResults (a,b,root);[/COLOR] .............
Thanks for all the help guys! I finally got it right with a little input from my instructor though. But again, thanks for taking the time to help.