Results 1 to 6 of 6
while loop problem...
- 09-29-2007 #1Just Joined!
- Join Date
- Sep 2007
- Posts
- 13
while loop
while loop problem
- 09-29-2007 #2Just Joined!
- Join Date
- Sep 2007
- Posts
- 13
while looping structure
Hey guys I have a problem with this while loop, its not working properly and I think that I might be typing it wrong but I don't how. please help me! Thanks... Anyways this is a calculator which is suppose to find the approximated square root value and using this algorithm, it is suppose to work. However in the while loop it apparently doesn't work for me.
Heres the code I put in:
[CODE:]
#include <stdio.h>
int main ()
{
double second, diff;
double first = 1.0; /* Given */
double number;
printf("please enter the number: ");
scanf("%lf", &number);
/* the formula that I am suppose to use to find the approx sqrt*/
second = .5 * (first + number/first);
diff = first - second;
/* while loop is suppose to run until the difference is less than .005*/
while (diff < .005)
{
/* since the diff is greater than .005, we put in second into first and then reiterating the same equation again*/
first = second;
second = .5 * (first + number/first);
diff = first - second;
}
printf("\n%lf\n", second);
return 0;
}
And when I plug in "3" for example, it comes up with 1.75, which it is suppose to be 1.73. But i have no idea how to change the loop to make that work. The loop apparently only runs one time and then it stops. I don't know why it doesn't work. Thanks for helping!
- 09-29-2007 #3
I shouldn't be doing your homework for you, but you have:
This means "run the following block of code repeatedly, as long as diff is less than .005".Code:while(diff<.005)
Is that what you want?
- 09-29-2007 #4Linux Enthusiast
- Join Date
- Apr 2004
- Location
- UK
- Posts
- 658
wje_lf's post is correct but diff will end up as a negative value the first time round. You need to account for that to get the absolute difference. Then you can talk about diff > 0.05.
Let us know how you get on,
Chris...To be good, you must first be bad. "Newbie" is a rank, not a slight.
- 09-29-2007 #5Linux Enthusiast
- Join Date
- Apr 2004
- Location
- UK
- Posts
- 658
It is actually against the forum rules to post homework questions./* the formula that I am suppose to use to find the approx sqrt*/
Let us know how you get on,
Chris...To be good, you must first be bad. "Newbie" is a rank, not a slight.
- 09-29-2007 #6Linux Enthusiast
- Join Date
- Apr 2004
- Location
- UK
- Posts
- 658
That question is awfully familiar
And it's still against the rules to post homework questions.
Let us know how you get on,
Chris...To be good, you must first be bad. "Newbie" is a rank, not a slight.


Reply With Quote