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

# Formatting math formulas

Greenhorn
Posts: 1
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?

Saloon Keeper
Posts: 3715
47
• 1
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.

Marshal
Posts: 57437
175
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:-

 If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS