C 11
Sqrt main.c Guest on 5th April 2021 10:45:19 AM
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <math.h>
  6.  
  7.  
  8. void st(float num, float lo, float hi);
  9.  
  10. main(int argc, char * argv[])
  11. {
  12.    float num;
  13.    float lo, hi;
  14.    int i, len;
  15.  
  16.    if(argc != 2) {
  17.       printf("error pgm arg \n");
  18.       exit(0);
  19.    }
  20.    len = strlen(argv[1]);
  21.    for(i = 0; i < len; i++)
  22.       if((!isdigit(argv[1][i]) && argv[1][i] != '.')){
  23.          printf("error arg should be digits \n");
  24.          return;
  25.    }
  26.    
  27.    num = atof(argv[1]);
  28.    printf("num = %f\n",num);
  29.    lo = 0;
  30.    hi = num + 1;
  31.  
  32.    st(num, lo, hi);
  33.  
  34. }
  35.  
  36.  
  37. void st(float num, float lo, float hi)
  38. {
  39.    float new;
  40.    float t;
  41.    t = lo*lo - num;
  42.    if (t < 0) t = t * -1;
  43.    
  44.    if (t < .001  ) {
  45.       printf("sqrt is %f\n",lo);
  46.       return;
  47.    }
  48.    else {
  49.       new = (lo + hi)/2;
  50.       if(new * new >  num)
  51.          hi = new;
  52.       else
  53.          lo = new;
  54. /*  printf("hi = %g lo = %g\n",hi, lo);       */
  55.       st(num, lo, hi);
  56.    }
  57. }

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.