Help Needed: Nothing is Printed

Newbie Member
27Apr2010,01:45   #1
Chimera9's Avatar
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
Pro contributor
27Apr2010,02:37   #2
virxen's Avatar
one error is this ---> while (s == sign(f(x))) {
and another is this -->return x*x - 1;
Chimera9 like this
Newbie Member
27Apr2010,02:46   #3
Chimera9's Avatar
I fixed those errors (thanks for catching those, by the way), but still nothing is being printed.
~ Б0ЯИ Τ0 С0δЭ ~
27Apr2010,11:58   #4
SaswatPadhi's Avatar
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
Go4Expert Member
27Apr2010,13:20   #5
davidk's Avatar
Place this line
Code: cpp
double root=FindRoot (a, b, h);
inside your PrintResults() function, or initialize 'root' variable inside main().
Chimera9 like this
Pro contributor
28Apr2010,00:17   #6
virxen's Avatar
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
Newbie Member
30Apr2010,00:48   #7
Chimera9's Avatar
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.