2

I've been reviewing my Java for a class I've taken for the whole year and haven't been doing well on. They have a separate review book called "Be Prepared." I want to see if I get the math behind this line.

result = (1 / 2) * n * (n + 1);    // result is 0.0

The thing is, this is basic basic basic. I need to know if I'm actually getting this. It looks like my like (1/2) is 0.5. That cast to an int is 0. That's why the whole thing is 0.0.

Am I right?

This book is how you get ready for the AP test. Anyone done eimacs who can help?

Braj
  • 46,415
  • 5
  • 60
  • 76
JackTrustsYou
  • 67
  • 1
  • 4
  • possible duplicate of [Fahrenheit to Celsius conversion yields only 0.0 and -0.0](http://stackoverflow.com/questions/7325882/fahrenheit-to-celsius-conversion-yields-only-0-0-and-0-0) – devnull Apr 13 '14 at 03:47
  • 1
    it's an integer division, not floating point division then truncating down – phuclv Apr 13 '14 at 03:53
  • If n is an int, then the result should be 0, not 0.0, unless result is of type double. – dansalmo Apr 13 '14 at 03:58

2 Answers2

7

(1 / 2) will return zero. both are integer and as per integer calculation it will return zero.

Try

result = (1.0 / 2) * n * (n + 1);  

Please have a look at :


In Java the result of each operation is decided by the higher type involved in calculation. It doesn't matter in what type are you assigning the result.

for e.g

double d = 10/3;

the value of d will be 3.0 only not 3.33.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 2
    he's not actually looking to make this work, he just wants confirmation that his thinking is correct. it's a strange question. – pennstatephil Apr 13 '14 at 03:48
2

Yes, and note that 999 / 1000 will also return 0. It's truncation, not rounding down.

Mdev
  • 2,440
  • 2
  • 17
  • 25