我有一个想实现的场景。 假设有4个人A,B,C和D。每个用户可以存入$ 10。扣除费用为1美元。所以最初我们有
A: 10
现在,当B加入时,B将向公司提供$ 1的扣除费,并且公司将与以前的客户共享该费用。所以。
A: 10+1
B: 9
现在,人C加入了,同样的事情发生了。现在,从C中扣除的1美元费用将在A和B中共享。
A: 10+1+0.5
B: 9+0.5
C: 9
可以有 n个用户,并且免费开始和扣除费用是可变的。我无法成功完成。这是我当前的代码。
<?php
$i;
$y;
$people = 10;
$stake = 1;
$dev = 0.1;
$counter = 0;
$inner_counter = 0;
$total_money = $stake * $people;
$remaining = $total_money * $dev;
for ($y = $people; $y > 0; $y--) {
echo "Total Deposit: " . $stake . " | Profit: ";
$inner_counter = 0;
for ($i = 0; $i < $y; $i++) {
echo($stake * $dev);
$counter++;
$inner_counter++;
}
echo '<br>';
echo " Inner:" . $inner_counter . "";
echo '<br>';
}
echo $counter;
echo '<br>';
for ($x = 0; $x <= $people; $x++) {
echo "($x / $counter)*$dev ";
echo '<br>';
}
我完全迷路了。如果有人可以告诉我一种更好的方法,那么它也会有所帮助。
答案 0 :(得分:4)
尝试一下。我认为代码中的注释和变量名使其很不言自明:
versions
输出:(version
):
$deposit = 10;
$fee = 1;
$people = 4;
$balances = array();
for ($p = 1; $p <= $people; $p++) {
// person p makes a deposit
$balances[$p] = $deposit;
// if more than one person, divide the fee by the preceding despositors
if ($p != 1) {
$balances[$p] -= $fee;
$split_fee = $fee / ($p - 1);
for ($i = 1; $i < $p; $i++) {
$balances[$i] += $split_fee;
}
}
}
print_r($balances);
输出($people = 4
):
Array
(
[1] => 11.833333333333
[2] => 9.8333333333333
[3] => 9.3333333333333
[4] => 9
)
修改
基于OP的反馈,以下是一个版本,该版本将关联数组作为输入而不是人数,并使用最终余额填充该数组:
$people = 10
输出:
Array
(
[1] => 12.828968253968
[2] => 10.828968253968
[3] => 10.328968253968
[4] => 9.9956349206349
[5] => 9.7456349206349
[6] => 9.5456349206349
[7] => 9.3789682539683
[8] => 9.2361111111111
[9] => 9.1111111111111
[10] => 9
)
答案 1 :(得分:2)
您可以循环计数并为每个array_slice分配费用,以将费用分配给n个人。
$people = ["A" => [], "B" => [], "C" => [], "D" => [], "E" => []];
$deposit = 10;
$fee =1;
$people["A"]["sum"] = $deposit;
for($i=1;$i<count($people);$i++){ // loop the same number of times as count of people
foreach(array_slice($people,0,$i) as $key => $p){ // only loop the number of people that should share the fee
if(!isset($people[$key]["sum"])) $people[$key]["sum"] = $deposit-$fee; // if it's the first round give them the starting sum
$people[$key]["sum"] += $fee/$i; // give them the percentage
}
}
$keys = array_keys($people);
$people[end($keys)]["sum"] = $deposit-$fee;
var_dump($people);
输出:
array(5) {
["A"]=>
array(1) {
["sum"]=>
float(12.083333333333)
}
["B"]=>
array(1) {
["sum"]=>
float(10.083333333333)
}
["C"]=>
array(1) {
["sum"]=>
float(9.5833333333333)
}
["D"]=>
array(1) {
["sum"]=>
float(9.25)
}
["E"]=>
array(1) {
["sum"]=>
int(9)
}
}