Results 1 to 5 of 5
Thread: C++ problem

Enjoy an ad free experience by logging in. Not a member yet? Register.



08122011 #1
 Join Date
 Aug 2011
 Posts
 38
C++ problem
The method I am using is like this:
Suppose I want to find sqrt s.
Then I set x_0=s
.
.
.
.
x_n= 0.5 * (x_{n1}+(s/(x_{n1}))
This is what i've written:
#include <iostream>
using namespace std;
int main()
{
double s, x, y;
cout << "Number sqrt of: ";
cin >> s;
for(x = s; xy >= 0.0000000001; x = y) {
y = 0.5 * (x + (s / x) );
cout << y << "\n";
}
return 0;
}
To ensure the program terminates, i'm performing x_nx_{n1} and if this is less than 0.0000000001, the program should terminate.
Unfortunately it isn't doing that. It keeps outputting 1.5 which is the first step.
Why isn't it looping?

08122011 #2
 Join Date
 Aug 2011
 Posts
 1
The method of calculation is wrong
I will do this:
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
double s, x, y = 0;
cout << "Number sqrt of: ";
cin >> s;
for( x = s; x != y; ) {
y = x;
x = ( (s / x) + x ) * .5;
cout << y << "\n";
}
return 0;
}
Saludos
pEpE

08122011 #3
 Join Date
 Aug 2011
 Posts
 51
The end of the for loop you set x=y and when you check xy >= 0.0000000001, it will always be false because xy = 0 and you then exit the loop. You need to compare the last guessed answer(your ? variable) to the current guessed answer(your y variable).

08192011 #4
 Join Date
 Aug 2011
 Posts
 38
Sorry for the late reply, I got a new computer!
Thanks histrungalot, it was a bit stupid of me doing that =S
Also thanks valdezpepe. Can you explain why you write int main(int argc, char **argv) instead of int main()? Your program still works if you just write int main(), is this for "completeness"?
EDIT: One last thing, why does your program terminate? If i'm reading this right, your program terminates when x != y which is every step. So wouldn't you fall out of the loop straight away?
Sorry for all these questions, i'm just trying to understand every step of what you've done.

08212011 #5
 Join Date
 Aug 2011
 Posts
 7
Using main(int argc, char **argv) is just telling the program to prepare for command line arguments to be passed to it. For instance, you could use this too extract and print the first word after the program name. (When executing in a terminal)
Code:if(argc > 0) { std::cout << argv[1] << std::endl; }
Code:>> program_name <word that you want printed>
Matt