Power functions: Illustration of return of float values

Program 42) Write a function power that computes x raised to the power y for integers x and y and returns doublr type value.
This program shows a power function that returns a double. The prototype declaration 
              double power (int, int) ;
appears in main, before power is called.

                                  PROGRAM

main ( )
 {
        int x, y ;       /*    Input data     */
        double power (int, int) ;    /*  Prototype declaration  */
     
        printf ("Enter x,y:") ;
        scanf ("%d %d", &x, &y) ;
        printf ("%d to power  %d is %f\n", x, y, power (x,y)) ;
  }
  double power (int x, int y) ;
  {
       double p ;
       p = 1.0 ;       /*    x to power zero    */

       if (y >= 0)
          while (y--)       /*   Computes positive powers   */
           p *= x ;
      else
          while (y++)     /*   Computes negative powers   */
            p /= x ;
      return (p) ;         /*    Returns double type   */
 }


Output:            Enter x, y : 16 2
                         16 to power 2 is 256.000000

                         Enter x, y : 16 -2
                         16 to power -2 is 0.003906

Another way to guarantee that power's type is declared before it is called in main is to define the power function before we define main. Power's type is then known from its definition, so we longer need its type declaration in main.

No comments:

Post a Comment