-10

Why it returns 0?

print(70 * (50 / 100));

70 * 0,5 = 35

I don't know why this is happening. Or did I make some stupid mistake either ... I don't know

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

4 Answers4

5

The 50/100 is a division between integers. Since 50<100, the result is 0 and consequently 70*(50/100) results in 0.

If you want to avoid this, you have to cast one of them as a double.

70 * (50 / (double)100)

or

70 * ((double) 50/ 100)
Christos
  • 53,228
  • 8
  • 76
  • 108
2

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2.

So on 50/100 is equal to 0.35 and because you are diving two Integers, it will ignore decimal places so it's gonna be a zero - 0, so computer see it as : (ignoring .35)

70 * 0 = 0

P.S

Maybe you could explore little bit about invoking Decimal.Divide, your int arguments get implicitly converted to Decimals so .35 won't be ignored.

You can also enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.:

int a = 42;
int b = 23;
double result = (double)a / b;

That's how it comes.. :)

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
1

Because / will output int and not double value. The result should be 0.5 and 0 will be taken as int then it will be multiplied by 70 and the result will be 0.

You need to make a cast as follows :

double x = 50/(double)100 ;

Then:

print(70 * x);
Rose
  • 349
  • 3
  • 17
-3

50 / 100 is 0 and 70 * 0 is 0.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • You have over 200,000 Meaningless Internet Points and this was still the best answer you could give? – Draco18s no longer trusts SE Jul 04 '17 at 03:15
  • Thank you very much for your constructive criticism and your extensive and detailed explanation about what is wrong with my answer. Unfortunately, I haven't been able to find your superior answer to learn from your experience, would you care to share it? – Jörg W Mittag Jul 04 '17 at 08:36
  • 1
    Every other answer on this page is more detailed than yours. Yours imparts no explanatory information content what so ever. I thought you would know that already, being a rather...well respected...SO user. – Draco18s no longer trusts SE Jul 04 '17 at 17:16
  • Agreed, this is a pretty terrible answer. – DavidG Jul 28 '17 at 16:15