programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# This should be easy, but its not working

Greenhorn
Posts: 1
Hi everyone, I'm super new to Java and taking an online course. I'm really struggling as the class is very poorly put together. I'm at the point where I have to do my first assignment and a question that I think should be easy is giving me trouble.

The question is:
Write a program that computes the following expression up to four (4) decimal places:
(1/10) + (2/9) + (3/8) + (4/7) + (5/6) + (6/5) + (7/4) + (8/3) + (9/2) + (10/1)

I know the correct answer is 22.2219, but when I do my program is comes up with 18.0000

I put the expression above into a double variable and when I print the variable I get 18.0000.

My instructor gave me a hint that I need to use a for-loop and its not as straight forward as it seems, but I dont understand what they want.

Any help would be appreciated.

Thanks

Bartender
Posts: 2155
46
1/10 is an integer division
You can check that it gives you 0 as a result.
If you want to calculate it correctly you should write is as a double division.
That is 1.0 / 10.0.

And welcome to the Ranch!

Marshal
Posts: 58470
178
1 ÷ 10 is 1 ÷ (11 - 1)
2 ÷ 9 is 2 ÷ (11 - 2)
3 ÷ 8 is 3 ÷ (11 - 3)

etc

I might prefer a while loop myself.

…and welcome to the Ranch

Campbell Ritchie
Marshal
Posts: 58470
178

Cole Pringle wrote: . . . 22.2219 . . .

1/10+2/9+3/8+4/7+5/6+6/5+7/4+8/3+9/2+10/1 = 22.21865079365079365079

You should get 22.2187

lowercase baba
Bartender
Posts: 12613
50
• 1
NEED to use a for loop?

no. Not at all. Just plain wrong.