Java中的整数除法 [英] Division of integers in Java

查看:35
本文介绍了Java中的整数除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基本问题,但我找不到答案.我研究了浮点运算和其他一些主题,但似乎没有解决这个问题.我确定我只是用错了术语.

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.

基本上,我想取两个数量 - 已完成数量和总数 - 并将它们除以得出一个百分比(已完成的数量).数量是longs.设置如下:

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

我尝试将结果重新分配给双精度值 - 它打印 0.0.我哪里出错了?

I've tried reassigning the result to a double - it prints 0.0. Where am I going wrong?

顺便说一句,下一步是将这个结果乘以 100,我认为一旦跨过这个小障碍,这应该很容易.

Incidentally, the next step is to multiply this result by 100, which I assume should be easy once this small hurdle is stepped over.

顺便说一句,这里不是家庭作业,只是简单的老式 numskull-ness(也许今天编码太多了).

BTW not homework here just plain old numskull-ness (and maybe too much coding today).

推荐答案

转换输出为时已晚;计算已经在整数算术中进行了.您需要将 inputs 转换为 double:

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);

请注意,您实际上不需要转换两个的输入.只要其中一个是double,另一个就会被隐式转换.但为了对称,我更喜欢两者兼而有之.

Note that you don't actually need to convert both of the inputs. So long as one of them is double, the other will be implicitly converted. But I prefer to do both, for symmetry.

这篇关于Java中的整数除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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