Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Help Needed: Nothing is Printed (http://www.go4expert.com/forums/help-printed-t21900/)

Chimera9 27Apr2010 01:45

Help Needed: Nothing is Printed
 
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.

virxen 27Apr2010 02:37

Re: Help Needed: Nothing is Printed
 
one error is this ---> while (s == sign(f(x))) {
and another is this -->return x*x - 1;

Chimera9 27Apr2010 02:46

Re: Help Needed: Nothing is Printed
 
I fixed those errors (thanks for catching those, by the way), but still nothing is being printed.

SaswatPadhi 27Apr2010 11:58

Re: Help Needed: Nothing is Printed
 
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.

davidk 27Apr2010 13:20

Re: Help Needed: Nothing is Printed
 
Place this line
Code: cpp

double root=FindRoot (a, b, h);

inside your PrintResults() function, or initialize 'root' variable inside main().

virxen 28Apr2010 00:17

Re: Help Needed: Nothing is Printed
 
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 30Apr2010 00:48

Re: Help Needed: Nothing is Printed
 
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.


All times are GMT +5.5. The time now is 11:38.