21

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

John
  • 15,990
  • 10
  • 70
  • 110
arberb
  • 960
  • 3
  • 14
  • 25

5 Answers5

47

What you could do is force it to divide a and b as doubles thus:

int x = (int) (((double) a / (double) b) * 100);
edwoollard
  • 12,245
  • 6
  • 43
  • 74
ridecar2
  • 1,968
  • 16
  • 34
10

Integer division has no fractions, so 500 / 1000 = 0.5 (that is no integer!) which gets truncated to integer 0. You probably want

int x = a * 100 / b;
Simon Urbanek
  • 13,842
  • 45
  • 45
6

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
Tejs
  • 40,736
  • 10
  • 68
  • 86
3

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.

cambraca
  • 27,014
  • 16
  • 68
  • 99
0

Simplest, most effective way I found:

double x = (double) a / (double) b