What's Here?
- Members: 149,631
- Replies: 506,753
- Topics: 79,851
- Snippets: 2,666
- Tutorials: 706
- Total Online: 2,084
- Members: 80
- Guests: 2,004
|
Shows how to write a method like pow() without the use of <math.h>
|
Submitted By: gabehabe
|
|
Rating:
  
|
|
Views: 453 |
Language: C
|
|
Last Modified: October 5, 2008 |
Snippet
/*
* A simple exponent function~ similar to pow()
* Author: Danny Battison
* Contact: gabehabe@googlemail.com
*/
double exponent(double x, double y)
{
int i; // use for the loops!
if (y == 0) return 1; // power of 0 always returns 1
double total = x; // the return value
if (y > 0) // we should multiply
for (i = 1; i < y; i++)
total *= x; // increase total
else // y < 0 (we should divide)
for (i = 0; i <= y*-1; i++)
total /= x;
return total;
}
/** EXAMPLE USAGE **/
#include <stdio.h>
int main()
{
printf("%.2f\n",exponent (- 2,- 2)); // result will be 0.25
printf("%.2f",exponent (2, 2)); // result will be 4.00
return 0; // successful execution
}
Copy & Paste
|
|
|
Be Social
Programming
Web Development
Reference Sheets
Bye Bye Ads
Monthly Drawing
Top Contributors
Top 10 Kudos This Month
|