Advertisement
Guest User

squareroot.c

a guest
Apr 18th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main(void)
  4. {
  5.     /* ---------Declerations--------- */
  6.     float num; //number to find square root of
  7.     double root; //the result of the calculation
  8.     double max = 1000; //The highest guess
  9.     double min = 0; //The lowest guess
  10.     int imaginary = 0; // 0 for real, 1 for imaginary
  11.    
  12.     /*---------Input---------*/
  13.    
  14.     printf("What number would you like to find the square root of? ");
  15.     scanf("%f", num);
  16.    
  17.     /*---------Calculations---------*/
  18.    
  19.     if(num<0)
  20.     {
  21.         imaginary = 1;
  22.         num = -num;
  23.     }
  24.     if(num>1)
  25.     {
  26.         max = num; //Highest possible root of a counting number
  27.     }
  28.     else
  29.     {
  30.         max = 1;
  31.     }
  32.     while (max-min > num/1000000000000000)
  33.     {
  34.         root = (max+min)/2;
  35.         if(root*root > num)
  36.         {
  37.             max = root;
  38.         }
  39.         else if(root*root < num)
  40.         {
  41.             min = root;
  42.         }
  43.         else if(root*root == num)
  44.         {
  45.             max=min;
  46.         }
  47.         else
  48.         {
  49.             printf("An error has occured, please contact developer.");
  50.             return 0;
  51.         }
  52.     }
  53.    
  54.     /*---------Output---------*/
  55.    
  56.     printf("The square root of %lf is %lf", num, root);
  57.     if(imaginary==1)
  58.     {
  59.         printf("i/n");
  60.     }
  61.     else
  62.     {
  63.         printf("/n");
  64.     }
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement