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?

3
  • possible duplicate of Fahrenheit to Celsius conversion yields only 0.0 and -0.0 Commented Apr 13, 2014 at 3:47
  • 1
    it's an integer division, not floating point division then truncating down Commented Apr 13, 2014 at 3:53
  • If n is an int, then the result should be 0, not 0.0, unless result is of type double. Commented Apr 13, 2014 at 3:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

he's not actually looking to make this work, he just wants confirmation that his thinking is correct. it's a strange question.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.