如何计算向量中单个元素占所有元素之和的百分比<float>

How to calculate the percentage of a single element in the sum of all elements in a vector<float>

我有一个 vector<float>a = {1,2,3,4,5,6,7,8,9} 对于每个元素,我想获得每个值在总和中的百分比。 这意味着最终结果应该是这样的 vector<float>b = {2.2%,4.4%,6.6%,8.8,11.1%,13.3%,15.6%,17.8%,20%}

数组的大小不确定。以上只是一个例子。

你需要先像这样先对整个数组求和:

float sum = 0;
for(size_t i =0; i<a.size(); i++) {
    // add to sum. I'll let you figure this part out
}

然后,一旦您知道 sum,您只需再次循环并将 vector/array 中的每个变量除以 sum。我也会让你弄清楚那部分。


编辑:其实我错了。这会给你一个概率,而不是一个真实的百分比。如果你想要百分比,那么你需要乘以 100。这会将 0.05 之类的东西转换为 5(隐含百分比)。您可以通过执行以下操作在与原始除法相同的循环中执行此操作:

percentage = (item / sum) * 100; // () not necessary here, I think, but just for clarity...

首先您需要计算总数或总和:

float total = std::accumulate(a.begin(), a.end(), 0.0f);

接下来,您需要计算每一项的百分比:

const unsigned int quantity = a.size();
for (unsigned int i = 0; i < quantity; ++i)
{
  float percentage = (a[i] * 100.0f) / total;
  cout << percentage << ", ";
}
cout << endl;