[英]Dividing two integers in Java gives me 0 or 100?
I'm trying to divide two integers and multiply by 100 but it keeps giving only 0 or 100. Can someone help me?我试图将两个整数相除并乘以 100,但它一直只给出 0 或 100。有人可以帮助我吗?
int x= (a/b)*100;
if a was 500 and b was 1000 it would give me 0. The only time it will give me 100 is if a>=b.如果 a 是 500 而 b 是 1000,它会给我 0。它会给我 100 的唯一时间是如果 a>=b。 How can I fix this?
我怎样才能解决这个问题?
Thanks谢谢
您可以做的是强制它将a
和b
划分为双精度数,因此:
int x = (int) (((double) a / (double) b) * 100);
整数除法没有分数,所以 500 / 1000 = 0.5(这不是整数!)它被截断为整数 0。你可能想要
int x = a * 100 / b;
This sounds like you are not correctly typing your variables;这听起来像是您没有正确输入变量; two integer divisions result in an integer, not a float or double.
两个整数除法产生一个整数,而不是浮点数或双精度数。 For example:
例如:
(int)3 / (int)5 = 0
(float)3 / (float)5 = 0.6
Try this:试试这个:
int x = a * 100 / b;
The idea is, you are first doing a / b
, and because it's an integer operation, it'll round the result to 0
.这个想法是,你首先做
a / b
,因为它是一个整数运算,它会将结果四舍五入到0
。 Doing a * 100
first should fix it.首先执行
a * 100
应该可以修复它。
我发现的最简单、最有效的方法:
double x = (double) a / (double) b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.