Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Formatting math formulas  RSS feed

 
Emily Burgardt
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very new to Java, and I know this is a very simple question, but:

I was working on a program that converts Fahrenheit to Celsius and was struggling to figure out why my output was always "0". Eventually I figured out it was a formatting issue.

I ended up having to change my formula from this:
celsius = ((5 / 9) * (fahrenheit - 32));

To this:
celsius = ((fahrenheit - 32) * 5) / 9;

It fixed my problem, but I'd still like to know for future reference - is there any particular reason why the first one wasn't working for me? Am I missing something obvious here?
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your culprit is 5/9. This is done in integer arithmetic and yields zero.

Try
celsius = ((5.0 / 9.0) * (fahrenheit - 32));

If celsius is defined as an int then you'll have to cast the result to an int before assigning it to celsius.
 
Campbell Ritchie
Marshal
Posts: 55678
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

To expand what CB said: integer division follows a convention which goes back sixty years: the quotient is rounded towards 0. If you divide 999999999 by 1000000000 you don't get it rounded up to 1, but rounded towards 0:-
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!