java 初学者Java问题(int,float)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3714066/
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-10-30 03:07:54  来源:igfitidea点击:

Beginners Java Question (int, float)

java

提问by bitmoe

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

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?

所以当我运行代码来显示fractionCinema 时,它只给我零。如果我将所有整数更改为双精度,那么它就会给我我正在寻找的东西。但是,我在其他地方使用了 Cinema、pc 和 total,它们必须显示为整数,而不是小数。我该怎么办?

回答by SLaks

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

当您将两个整数相除时(例如,2 / 3),Java 执行整数除法,并截断小数部分。
因此,2 / 3 == 0

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

您需要double通过将任一操作数强制转换为double.

For example:

例如:

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

回答by David R Tribble

Try this instead:

试试这个:

int  cinema, total;
int  fractionCinema;

fractionCinema = cinema*100 / total;   //percent cinema

For example, if cinema/(double)totalis 0.5, then fractionCinemawould be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.

例如,如果cinema/(double)total是 0.5,那么fractionCinema就是 50。并且不需要浮点运算;所有的数学运算都是使用整数算术完成的。

Addendum

附录

As pointed out by @user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:

正如@user949300 所指出的,上面的代码四舍五入到最接近的整数。要“正确”舍入结果,请使用以下命令:

fractionCinema = (cinema*100 + 50) / total;    //percent cinema

回答by NullUserException

When you divide two ints, Java will do integer division, and the fractional part will be truncated.

当你除以两个ints 时,Java 会做整数除法,小数部分会被截断。

You can either explicitly cast one of the arguments to a double via cinema/(double) totalor implicitly using an operation such as cinema*1.0/total

您可以将其中一个参数显式转换为 double viacinema/(double) total或隐式使用诸如cinema*1.0/total

回答by L0PES_CP_1217

As some people have already stated, Java will automatically cut off any fractional parts when doing division of integers. Just change the variables from int to double.

正如一些人已经说过的那样,Java 在进行整数除法时会自动切掉任何小数部分。只需将变量从 int 更改为 double 即可。