Java中整数的划分 [英] Division of integers in Java
问题描述
基本上,我想采取两个数量 - 完成和总数 - 并将它们分成一个百分比已经完成了多少)。数量是
long
s。这是设置: long completed = 25000;
总计= 50000;
System.out.println(已完成/总计); //打印0
我已经尝试将结果重新分配给一个double - 打印 0.0
。顺便提一句,下一步是把这个结果乘以100,我认为一旦这个小障碍跨越,我认为应该是容易的。
(b)b
顺便提一句,这里不是作业,只是简单的旧的numskull-ness(也许今天的编码太多了)。 解决方案转换输出太晚了;计算已经发生在整数运算中。您需要将输入转换为 double
:
的System.out.println((双)完成/(双)总计);
请注意,您实际上并不需要转换 只要一个是 double
,另一个将被隐式转换。但我更喜欢做这两个,为对称。
This is a basic question but I can't find an answer. I've looked into floating point arithmetic and a few other topics but nothing has seemed to address this. I'm sure I just have the wrong terminology.
Basically, I want to take two quantities - completed, and total - and divide them to come up with a percentage (of how much has been completed). The quantities are long
s. Here's the setup:
long completed = 25000;
long total = 50000;
System.out.println(completed/total); // Prints 0
I've tried reassigning the result to a double - it prints 0.0
. Where am I going wrong?
Incidentally, the next step is to multiply this result by 100, which I assume should be easy once this small hurdle is stepped over.
BTW not homework here just plain old numskull-ness (and maybe too much coding today).
Converting the output is too late; the calculation has already taken place in integer arithmetic. You need to convert the inputs to double
:
System.out.println((double)completed/(double)total);
Note that you don't actually need to convert both of them; so long as one is double
, the other will be implicitly converted. But I prefer to do both, for symmetry.
这篇关于Java中整数的划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!