Java中整数的划分 [英] Division of integers in Java

查看:169
本文介绍了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 longs. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆