我正在分发代币,但它们并未全部分发。我有多个百分比并获得了为该百分比提供的代币数量,但它们不等于总数。
例子:
int tokens = 50;
double[] percentages = new double[] {0.3725, 0.219, 0.115, 0.2935};
int total = 0;
for(double d : percentages){
int amount = (int) (tokens * d);
total += amount;
}
虽然总数是 47。我也尝试用 Math.round 对其进行舍入
for(double d : percentages){
double rounded = Math.round(d * 100);
int amount = (int) (tokens * (rounded / 100));
total += amount;
}
总数是49
我似乎永远达不到 50,它总是低于或高于 50。我想尽可能均匀地分配这些代币。如果你能帮忙,请做!
最佳答案
使用double
total
。使用int会导致小数信息丢失
double total = 0;
for(double d : percentages){
double amount = (tokens * d);
total += amount;
}
关于java - 总百分比不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38566963/