Help Needed: Nothing is Printed

Chimera9's Avatar, Join Date: Apr 2010
Newbie Member
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.

Last edited by shabbir; 27Apr2010 at 09:41.. Reason: Code blocks
0
virxen's Avatar, Join Date: Nov 2009
Pro contributor
one error is this ---> while (s == sign(f(x))) {
and another is this -->return x*x - 1;
Chimera9 like this
0
Chimera9's Avatar, Join Date: Apr 2010
Newbie Member
I fixed those errors (thanks for catching those, by the way), but still nothing is being printed.
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
Found the error
Change :
Code: CPP
double root=FindRoot (a, b, h);
to
Code: CPP
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.
Chimera9 like this
0
davidk's Avatar, Join Date: Mar 2010
Go4Expert Member
Place this line
Code: cpp
double root=FindRoot (a, b, h);
inside your PrintResults() function, or initialize 'root' variable inside main().
Chimera9 like this
0
virxen's Avatar, Join Date: Nov 2009
Pro contributor
another error is this

Quote:
for (x=0; x < b; x=(a+b)/h)
return x;
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>
 
//double a;
//double b;
//double h;
  .......
int main( ) {
double a=-2,b=0,h=0.01;
    double root=FindRoot (a, b, h);
    PrintResults (a,b,root);
.............
Chimera9 like this
0
Chimera9's Avatar, Join Date: Apr 2010
Newbie Member
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.