gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:00:46 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com