0
int value = 10 * (50 / 100);

The expected answer is 5, but it is always zero. Could anyone please give me detail explanation why it is?

Thanks much in advance.

Mohamed Thaufeeq
  • 1,667
  • 1
  • 13
  • 34

3 Answers3

3

Because the result of 50/100 is 0 .

50/100 is equals to int(50/100) which returns 0.

Also, if you want to return 5, use this:

int value = (int)(10 * (50 / 100.0));

The result of (50/100.0) is 0.5.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

Because you're doing an integer division: (50 / 100) gives 0

Try this:

int value = (int)(10 * (50 / 100.0));

Or reverse the multiply/division

int value = (10 * 50) / 100;

So it's getting multiplied before the divide

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
1

You make operation on int values. 50/100 in int is 0.

emish89
  • 696
  • 8
  • 25