xl JAMKA lx Posted September 10, 2019 Share Posted September 10, 2019 (edited) 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 September 10, 2019 by xl JAMKA lx Quote Link to comment Share on other sites More sharing options...
Homer Posted September 10, 2019 Share Posted September 10, 2019 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) 3 Quote Link to comment Share on other sites More sharing options...
xl JAMKA lx Posted September 10, 2019 Author Share Posted September 10, 2019 ah okay, yeah Fahrenheit was defined as a double variable Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.