0

How to make a recursion power function witch allows you to use fractions as the power ?

for exemple when I have 3 to the 1/3 power. My function: template <class T,class U> U power(T x,U y) { if(y==0) return 1; else return x * power(x,y-1); // works only when y=int }

20th Nov 2016, 1:30 AM
Mateusz Antczak
Mateusz Antczak - avatar
2 odpowiedzi
0
Here's what happens: Let's say you make y a float with the value 1/3 = 0.333 The second time the template runs, y is now a negative value, and it will keep running and keep subtracting 1 from y, so you will never hit 0 with a fractional/decimal value. Instead change y==0 to y<=0 and it should work, I just tested it.
20th Nov 2016, 2:12 AM
scott johnson
scott johnson - avatar
0
My output is the same as the x number. I don't know why. //edit Outputs: 27^0.333=27 27^0.5=27 2^1.5=4 2^2.5=8 Doesn't work, It's rounding up y ?
20th Nov 2016, 2:35 AM
Mateusz Antczak
Mateusz Antczak - avatar