Welcome to The Forum

Register now to gain access to all of our features. Once registered and logged in, you will be able to create topics, post replies to existing threads

Question with code equation


xl JAMKA lx
 Share

Recommended Posts

so, I was doing homework and The code for C#

celsius = (fahrenheit - 32) * 5 / 9 ;       //equation to convert Fahrenheit to Celsius

//celsius = 5 /9 * (fahrenheit - 32);  <----Doesn't work.

can someone explain why the second one doesn't work?

Homework is done and turned in.  I just wanna know why it doesn't work.

Edited by xl JAMKA lx
Link to comment
Share on other sites

Order of Operations (Source)

Assuming your fahrenheit variable is likely a double or a float.

Lets say its a float for example:

 

celsius = (fahrenheit - 32) * 5 / 9

(fahrenheit - 32) is executed first and results in a float value

Next the float value is * 5, which results in a float type value again

Next the float value is / 9, which results in a float type value again and thats the end result.

 

celsius = 5 /9 * (fahrenheit  - 32)

(fahrenheit - 32) is executed first because of highest Precedence (Source)

However next, (5 / 9) is executed and returns an integer 0

5/9 performs an integer division—that is, it always discards the fractional part—so it will always return 0

 

The integer type issue can be fixed by:

celsius = 5f / 9 * (fahrenheit  - 32)

or if fahrenheit is a double, then:

celsius = 5.0 / 9 * (fahrenheit  - 32)

  • Like 3
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share