I'm trying to divide two integers and multiply by 100 but it keeps giving only 0 or 100. Can someone help me?
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. 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
. Doing a * 100
first should fix it.
我发现的最简单、最有效的方法:
double x = (double) a / (double) b
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.