Java 数学(运行时内存百分比)

标签 java math runtime percentage

我确定我在这里犯了某种极其愚蠢的错误。 我有这段代码:

private static String generateRAM()
{
    final long RAM_TOTAL = Runtime.getRuntime().totalMemory();
    final long RAM_FREE = Runtime.getRuntime().freeMemory();
    final long RAM_USED = RAM_TOTAL - RAM_FREE;
    final long RAM_TOTAL_MB = RAM_TOTAL / 8 / 1024;
    final long RAM_FREE_MB = RAM_FREE / 8 / 1024;
    final long RAM_USED_MB = RAM_USED / 8 / 1024;
    final double RAM_USED_PERCENTAGE = (RAM_USED / RAM_TOTAL) * 100;
    return RAM_TOTAL_MB + "MB TOTAL / " + RAM_FREE_MB + "MB FREE / " + RAM_USED_MB + "MB USED (" + RAM_USED_PERCENTAGE + "%)"; 
}

返回:

15440MB TOTAL / 11809MB FREE / 3630MB USED (0.0%)

百分比显然不正确。 这是怎么发生的? 据我所知,我做的所有数学都是正确的。 如果我将给定的数字输入计算器并自己计算百分比,我会得到 23.5,这是我的预期结果。

我确定我刚刚犯了一个我会自责的可怕错误,有人可以启发我吗?

最佳答案

final double RAM_USED_PERCENTAGE = (RAM_USED / RAM_TOTAL) * 100;

因为整数除法。将其中一种类型转换为 double。

例子:

final double RAM_USED_PERCENTAGE = ((double)RAM_USED / RAM_TOTAL) * 100;

根据 JLS 15.17.2. Division Operator /

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

关于Java 数学(运行时内存百分比),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14529890/

相关文章:

java - 在 IntelliJ IDEA 中创建 Java Gradle 项目并构建 .jar 文件 - 如何?

java - 动态加载 EMF 模型时出错

java - 根据优先级重新排列数组

python - 您如何像 Mathematica 那样执行这种不正确的积分?

java - 你如何获得绝对值和平方根

Gradle 为运行时依赖创建循环依赖

css - 如何在不将图像嵌入外部样式表的情况下将图像用于皮肤

java - 我如何找出所有格表达以及它们之间的联系?

Java - 提高简单素数 validator 的性能

c# - 在运行时动态修改样式(添加触发器)