![](/img/trans.png)
[英]How to round down money and then distribute remaining pennies among ranked players?
[英]How to distribute money to a list with x people?
我被困在一个问题上。 我必须将 x 数量的钱分配给 x 个人的名单。 我有两节课。 第一个是Person ,具有 Age、Money、Name 和 Surname 属性。 另一个 class 应该将钱分配到列表中:
public class MoneyCalculator
{
List<Person> People { get; set; } = new List<Person>();
public void MoneyToDistribute(int money)
{
for (int i = 0; i < money; i++)
{
foreach (Person person in People)
{
person.Money++;
money--;
}
}
}
当我单击一个按钮时,我希望用户输入任意数量的人,并设置除金钱之外的所有属性。 所以这是将人员添加到我的列表中:
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
age = int.Parse(txtBoxAge.Text);
name = txtBoxName.Text;
surname = txtBoxSurName.Text;
Person person = new Person()
{
Age = age,
Money = // should I even put it here?
FirstName = name,
Surname = surname
};
People.Add(person);
lstBoxPeople.ItemsSource = null;
lstBoxPeople.ItemsSource = People;
}
最后,我想为列表中的每个人设置属性 Money。 我知道目前这对财产货币没有任何作用,但我不明白如何使它起作用:
private void btnDistrib_Click(object sender, RoutedEventArgs e)
{
money = int.Parse(txtBoxMoney.Text);
MoneyCalculator.MoneyToDistribute(money);
}
我到底做错了什么? 我认为这与我的列表以及何时添加人员有关,但我不确定。 如果这有什么不同,我的 MainWindow 中已经有以下内容。
List<Person> People = new List<Person>();
MoneyCalculator MoneyCalculator = new MoneyCalculator();
您有两个具有相同名称的不同列表:人员。 如果您在MoneyCalculator
中调用People
,您将参考其他列表,即在调用此 class 之外的People
时。
MoneyToDistribute
也可以简化
public void MoneyToDistribute(int money)
{
int amountForPerson = money / People.Count;
int peopleWithExtra = money - People.Count * amountForPerson;
for (int i=0; i < People.Count; i++)
{
Person person = People[i];
person.Money += amountForPerson;
if(i < peopleWithExtra) person.Money++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.