I'd like to be able to make a function x^n, where x is a float, and n is a positive integer.
What about something like this?:
Code:int a; float x_n=1; float nthpower(float x, int n) { for(a=0;a<=n;a++); x_n=x_n*x; }
This is a discussion on Making a function x^n within the C Programming forums, part of the General Programming Boards category; I'd like to be able to make a function x^n, where x is a float, and n is a positive ...
I'd like to be able to make a function x^n, where x is a float, and n is a positive integer.
What about something like this?:
Code:int a; float x_n=1; float nthpower(float x, int n) { for(a=0;a<=n;a++); x_n=x_n*x; }
Last edited by bertazoid; 10-21-2008 at 06:24 AM.
Except a and x_n need to be defined inside the function, rather than at global scope. You also need to return your answer. And your for-loop goes one too many times.
There is already such a function, called pow().
First of all what you do is wrong. you would want:
1) You need int a, float x_n inside the functionCode:float nthpower(float x, int n) { int a; float x_n=1; for(a=0;a<n;a++); x_n=x_n*x; return x_n; }
2) You ned < not <=
3) You need of course a return;
4) You need to check for n begin negative. If it's 0 it's OK
5) There are might be more optimized ways to do so
Last edited by C_ntua; 10-21-2008 at 06:40 AM.
The semicolon above is wrong too.Code:for(a=0;a<n;a++); x_n=x_n*x;
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
you can solve it by recursion:
Code:power (int x,int n) { if (n==0){ return 1; } else { return power(x,n-1)*x; } }
i cant understand where is my bug in this code
Code:#include <stdio.h> power (int x,int n); int main() { printf("%d",power(2,1); //i got a bug in this place i dont know why return 0; } int power (int x,int n) { if (n==0){ return 1; } else { return power(x,n-1)*x; } }
Do you mean the missing ) on the printf, or something else? A "bug" in my mind is not a typo that the compiler can detect, but something that causes incorrect behaviour (result, sequence of events, etc) compared to what you expect.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
oohhh such a foolishness
sorry
my recursion works