Code Snippets

  

C Source Code


Welcome to Dream.In.Code
Become an Expert!

Join 149,631 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,084 people online right now. Registration is fast and FREE... Join Now!





Exponent Function

Shows how to write a method like pow() without the use of <math.h>

Submitted By: gabehabe
Actions:
Rating:
Views: 453

Language: C

Last Modified: October 5, 2008

Snippet


  1. /*
  2. * A simple exponent function~ similar to pow()
  3. * Author: Danny Battison
  4. * Contact: gabehabe@googlemail.com
  5. */
  6.  
  7. double exponent(double x, double y)
  8. {
  9.     int i; // use for the loops!
  10.     if (y == 0) return 1; // power of 0 always returns 1
  11.  
  12.     double total = x; // the return value
  13.  
  14.     if (y > 0)  // we should multiply
  15.         for (i = 1; i < y; i++)
  16.             total *= x; // increase total
  17.  
  18.     else // y < 0 (we should divide)
  19.         for (i = 0; i <= y*-1; i++)
  20.             total /= x;
  21.     return total;
  22. }
  23.  
  24.  
  25. /** EXAMPLE USAGE **/
  26. #include <stdio.h>
  27.  
  28. int main()
  29. {
  30.     printf("%.2f\n",exponent(-2,-2)); // result will be 0.25
  31.     printf("%.2f",exponent(2,2)); // result will be 4.00
  32.     return 0; // successful execution
  33. }
  34.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month