Java long 除以 long 返回 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18117014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:29:47  来源:igfitidea点击:

Dividing long by long returns 0

java

提问by user1815823

I am trying to calculate % of used diskspace in Windows and totaldrive denotes total diskspace of c drive in Long and freedrive dentoes free space in Long.

我正在尝试计算 Windows 中已用磁盘空间的百分比,totaldrive 表示 Long 中 c 驱动器的总磁盘空间,而 freedrive 表示 Long 中的可用空间。

 long totaloccupied = totaldrive - freedrive;

Here calculating % of usage

这里计算使用百分比

 Long Percentageused =(totaloccupied/totaldrive*100);
 System.out.println(Percentageused);

The print statement returns 0. Can someone help as I am not getting the desired value

打印语句返回 0。有人可以帮忙,因为我没有得到所需的值

采纳答案by Lake

You are probably dividing a long with a long, which refers to (long/long = long) operation, giving a long result (in your case 0).

您可能正在将 long 与 long 相除,它指的是 (long/long = long) 操作,给出一个 long 结果(在您的情况下为 0)。

You can achieve the same thing by casting either operand of the division to a float type.

您可以通过将除法的任一操作数转换为浮点类型来实现相同的目的。

Long Percentageused = (long)((float)totaloccupied/totaldrive*100);

回答by Jason C

That will be evaluated left to right, the first integer division will return 0 (e.g. 8/10 evaluates to 0). Either convert values to floats or do 100*a/b. Floats will give you a more precise result.

这将从左到右计算,第一个整数除法将返回 0(例如 8/10 计算为 0)。将值转换为浮点数或执行 100*a/b。Floats 会给你一个更精确的结果。

回答by gdiazc

You are doing integer division! Since totaloccupiedis smaller than totaldrive, the division of both gives the answer 0. You should convert to double first:

你在做整数除法!既然totaloccupied小于totaldrive,两者的除法给出了答案0。您应该先转换为双精度:

double percentageUsed = 100.0 * totalOccupied / totalDrive;

Note that adding the decimal point to the 100ensures it is treated as a double.

请注意,将小数点添加到100确保它被视为double.