home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / IPOW.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  1KB  |  58 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  IPOW.C - Raise a number to an integer power
  5. **
  6. **  public domain by Mark Stephen with suggestions by Keiichi Nakasato
  7. */
  8.  
  9. #include "snipmath.h"
  10.  
  11. double ipow(double x, int n)        /* return x^n */
  12. {
  13.       double t = 1.0;
  14.  
  15.       if (!n)
  16.             return 1.0;    /* At the top. 0**0 = 1 */
  17.       if (n < 0)
  18.       {
  19.             n = -n;
  20.             x = 1.0/x;  /* error if x == 0. Good                        */
  21.       }                 /* ZTC/SC returns inf, which is even better     */
  22.       if (x == 0.0)
  23.             return 0.0;
  24.       do
  25.       {
  26.             if (n & 1)
  27.                   t *= x;
  28.             n /= 2;     /* KN prefers if (n/=2) x*=x; This avoids an    */
  29.             x *= x;     /* unnecessary but benign multiplication on     */
  30.       } while (n);      /* the last pass, but the comparison is always  */
  31.       return t;         /* true _except_ on the last pass.              */
  32. }
  33.  
  34. #ifdef TEST
  35.  
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38.  
  39. #ifdef __WATCOMC__
  40.  #pragma off (unreferenced);
  41. #endif
  42. #ifdef __TURBOC__
  43.  #pragma argsused
  44. #endif
  45.  
  46. main(int argc, char *argv[])
  47. {
  48.       double d;
  49.       int n;
  50.  
  51.       d = atof(argv[1]);
  52.       n = atoi(argv[2]);
  53.       printf("%f^%d = %f\n", d, n, ipow(d, n) );
  54.       return 0;
  55. }
  56.  
  57. #endif /* TEST */
  58.