开发者

How can I increment values by assigning different percentage

The question might be related more to math than to programming. I'll explain the question by an example. Let's say I have an array with 1开发者_Python百科00 items and I want to assign values to these items in such a way that the total of values in the first 80% of the items is 20% and the total of the values in the last 20% of the items is 80%. That is, the first 80% of the items get 20% and the rest get 80%. Knowing that the number of the items is determined at run time.

Is this possible?

Thanks.


Lets say total is 100. Asign 0.25 to first 80% (80 items). So sum of first 80 items will be 80 * 0.25 = 20 (it's 20% of total). Now assign 4 to rest 20% (20 items). So sum of last 20 items will be 20 * 4 = 80 (it's 80% of total) This is what you need in code.

double[] items = new double[100]; 
for (int i = 0; i < 80; i++) 
    items[i] = 0.25; 
for (int i = 80; i < 100; i++) 
    items[i] = 4; 


Surely.

Let total be 1, than 80% is 0.8. If 20 items sum up to 0.8, each of them gets 0.8/20 = 0.04. The rest 80 items get in total 0.2, each of them gets 0.2/80 = 0.01/4 = 0.0025.

double[] items = new double[100];
for (int i = 0; i < 20; i++)
    items[i] = 0.04;
for (int i = 20; i < 100; i++)
    items[i] = 0.0025;

The same applies for integers etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜