2016-06-14 17 views
0

因此,我正在尝试创建一个函数,它需要金额,百分比(小数)和时间,并返回金额的双倍。PHP函数递归地将一个百分比应用于金额

我希望得到的结果如下:

$amount = 10000 
$percentage = 1.1 
$times = 1 

所以..

elevateToPercentage($amount, $percentage, $times) = 10,000 * 1.1 = 11,000 
$times = 2 
elevateToPercentage($amount, $percentage, $times) = ((10,000 * 1.1) * 1.1) = 12,100 
$times = 4 
elevateToPercentage($amount, $percentage, $times) = ((((10,000 * 1.1) * 1.1) * 1.1) * 1.1) = 14,641 

private function elevateToPercentage($amount, $percentage, $times) { 
    $count = 0; 
    for($a = 0; $a <= $times; $a++) { 
     $count += ($amount * $percentage); 
    } 
    return $count; 
} 

我知道这是一个逻辑错误,但从来就已经太多,我似乎并没有工作了,现在:( 你们能帮帮我吗?

谢谢!

+1

'$ A> = $倍;'?!?你的意思是''='? http://php.net/manual/en/control-structures.for.php –

+0

@MarkBaker修正了这个例子。谢谢,看看我累了xD仍然没有做我需要的东西 – mkmnstr

+0

'$ count'是什么? –

回答

2

什么:

function elevateToPercentage($amount, $percentage, $times) { 
    if ($times == 1){ 
     return $amount * $percentage; 
    }else{ 
     return $percentage * elevateToPercentage($amount, $percentage, $times -1); 
    } 
} 
+0

这太好了!谢谢!我想标记两个答案都是正确的。 – mkmnstr

+0

Ravinder的答案也是正确的,但如果目标是使用递归函数,我的方法会更好。如果你不需要使用递归方法(比如如果这不是作业“使用递归函数......”),Ravinder的方法对于大多数人来说可能更易读。 – Dolfa

+0

你是对的。我会为你安排。 – mkmnstr

4

可以使用POW功能

function elevateToPercentage($amount, $percentage, $times) { 
    $multiple = pow($percentage, $times); 
    return number_format($amount*$multiple) ; 
} 
$amount = 10000; 
$percentage = 1.1; 
$times = 1; 
echo elevateToPercentage($amount, $percentage, $times); 

出把实现它:

$times = 1; 11,000 
$times = 2; 12,100 
$times = 4; 14,641 
+0

这样做。我不知道这个功能。谢谢! – mkmnstr