• Post Reply Bookmark Topic Watch Topic
  • New Topic

This should be easy, but its not working  RSS feed

 
Cole Pringle
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Paweł Baczyński
Bartender
Posts: 2074
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NEED to use a for loop?

no. Not at all. Just plain wrong.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!