初学者Java问题(int,float) [英] Beginners Java Question (int, float)

查看:117
本文介绍了初学者Java问题(int,float)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema

因此,当我运行代码来显示fractionCinema时,它只给我零。如果我将所有的整数改为双打,那么它就会给我我想要的东西。但是,我在其他地方使用影院,电脑和总计,它们必须显示为整数,而不是小数。我该怎么办?

So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?

推荐答案

当你划分两个整数时(例如, 2/3 ),Java执行整数除法,并截断小数部分。

因此, 2/3 == 0

When you divide two ints (eg, 2 / 3), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0.

您需要通过将操作数强制转换为<$来强制Java执行 double 除法c $ c> double 。

You need to force Java to perform a double division by casting either operand to a double.

例如:

fractionCinema = (cinema / (double)total) * 100;

这篇关于初学者Java问题(int,float)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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