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,617
  • 1
  • 12
  • 32

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
  • 44,345
  • 11
  • 88
  • 115
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
  • 19,966
  • 3
  • 36
  • 54
1

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

emish89
  • 645
  • 10
  • 25