如何计算数字列表的百分比?
How can I calculate percentages of a list of numbers?
这是我正在尝试计算的示例。
我在一个列表中有 4 个不同的项目,每个项目有多少。例如:
Box1 contains 3.2 items
Box2 contains 6.1 items
Box3 contains 4.0 items
Box4 contains 1.8 items
我想计算的是每个Box的百分比。结果看起来像:
Box1 contains 3.2 items = 17%
Box2 contains 6.1 items = 51%
Box3 contains 4.0 items = 24%
Box4 contains 1.8 items = 8%
Total = 100%
由于这个问题没有语言标签,我在Java中起草了一个解决方案。
计算项目总数:
double total= 0;
for(int i = 0; i < boxList.size(); i++)
{
total += boxList[i].getItems();
}
计算每个箱子所装物品的百分比:
for(int i = 0; i < boxList.size(); i++)
{
double ithPercentage = (boxList[i].getItems()/total) * 100.0d;
//output the result
}
在C#
中使用LINQ
var sum = list.Sum(item=>item.Quantity);
var pctList = list.Select(item=>item.Quantity/sum);
这是我正在尝试计算的示例。
我在一个列表中有 4 个不同的项目,每个项目有多少。例如:
Box1 contains 3.2 items
Box2 contains 6.1 items
Box3 contains 4.0 items
Box4 contains 1.8 items
我想计算的是每个Box的百分比。结果看起来像:
Box1 contains 3.2 items = 17%
Box2 contains 6.1 items = 51%
Box3 contains 4.0 items = 24%
Box4 contains 1.8 items = 8%
Total = 100%
由于这个问题没有语言标签,我在Java中起草了一个解决方案。
计算项目总数:
double total= 0;
for(int i = 0; i < boxList.size(); i++)
{
total += boxList[i].getItems();
}
计算每个箱子所装物品的百分比:
for(int i = 0; i < boxList.size(); i++)
{
double ithPercentage = (boxList[i].getItems()/total) * 100.0d;
//output the result
}
在C#
中使用LINQ
var sum = list.Sum(item=>item.Quantity);
var pctList = list.Select(item=>item.Quantity/sum);