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();
}

>> 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.

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();
}

>>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.

:/ 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();
}

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.