0

help please, i have to generate a funciton which generates the squareroot of any real number! I don't know what else I can do :(

#include <stdio.h>
#include <math.h>
double squareroot(double number)
 {
  double x[20];
  int count,count2;
  x[0] = 1;
  for (count = 0;count <= 20;count++)
   {
    while ((abs(x[(count2)-1]) - x[(count2)]) > 0.001)
     {
      x[(count2)+1] = (((x+number/x))/2);
      return x[(count2)+1];
     }
   }
 }

main()
{
getch();
}
3
Contributors
6
Replies
8
Views
11 Years
Discussion Span
Last Post by gxm
0

>> return x[(count2)+1];
the above is on the inside of the loop so the loop will only run once.

>>for (count = 0;count <= 20;count++)
this loop will count one too many times. the array only has 20 elements but the loop will run 21 times.

0

I arranged the code like this, but there is an error in line 15 invalid operands to binary /

#include <stdio.h>
#include <math.h>
float squareroot(float number)
 {
  float x[20];
  int count,count2;
  x[0] = 1;
  for (count = 0;count <= 19;count++)
   {
    while ((abs(x[(count2)-1]) - x[(count2)]) > 0.001)
     {
      x[(count2)+1] = (((x+(number/x)))/2);
     }
   }
  return x[(count2)+1];
 }

main()
{
float num =0;
printf("Enter a number : ");
scanf("%f",num);
printf("%f",squareroot(num));
getch();
}
0

>>return x[(count2)+1];
this is wrong. When the loop ends, the value of count2 will be 20. x[21] is referencing too nonexistant elements of the array.

0

:/ i'm really lost with this one, made the following arrangements but nothing works:

#include <stdio.h>
#include <math.h>
float squareroot(float number)
 {
  float x[20];
  int count;
  int count2 = 1;
  x[0] = 1;
  x[1] = (x+(number/x))/2;
  for (count = 0;count <= 19;count++)
   {
    while ((abs(x[(count2)-1]) - x[(count2)]) > 0.001)
     {
      x[(count2)+1] = ((x+(number/x)) /2);
      count2++;
     }
   }
  return x[(count2)+1];
 }

main()
{
float num =0;
printf("Enter a number : ");
scanf("%f",num);
printf("%f",squareroot(num));
getch();
}
0

that error was solved, still got one though, but i'll try to solve it first, thanks for your help!

0

you can use recursion to ensure within the suitable times you can get the right number

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.