java - 总百分比不正确

标签 java math rounding

我正在分发代币,但它们并未全部分发。我有多个百分比并获得了为该百分比提供的代币数量,但它们不等于总数。

例子:

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/

相关文章:

java - 优雅的解决方案?

python - 在 scipy/numpy 中求解具有已知 y 的多项式的 x 值

c++ - 如何向下舍入到最接近的 10 的幂?

c++ - 更高级地使用 ceil() 函数

C# 为什么 string.format 将浮点值四舍五入到最接近的第 10 位?

java - 在Java中从字符串中删除字符

Windows 上的 Java 时钟精度 : 15-16ms

java - 防止后退按钮退出 Cordova 插件内的 Android 应用程序

c# - 从大小为 n 的列表中查找哪些数字与另一个数字相加的算法

generics - F# 有通用算术支持吗?