2016-06-14 43 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