I'm still very much a programming newbie, so maybe this all makes perfect sense but it wasn't the behaviour I was expecting. I wrote a Celsius to Fahrenheit converter to show someone the basics of coding, here it is:
Now, the parentheses around 9/5 are completely unnecessary, but I put them in thinking it wouldn't make any difference. The code gave me the wrong answers and I think it's because it's actually treating the result of (9/5) as an integer and thus truncating it.Code:#include <iostream> using namespace std; int main() { float var1; cout << "Please enter degrees Celcius: "; cin >> var1; float var2 = var1 * (9/5) + 32; cout << var1 << " degrees Celsius = " << var2 << " degrees Fahrenheit"; return 0; }
Of course, I just removed the parentheses but I'm interested to know why it behaves this way and if there is a way to get around it.
I've been hobby programming in C++ on and off for a year or two, I wondered why I'd never encountered this issue before but then I realized to my chagrin that everything I'd been playing with was discrete and I'd actually never used a float in C++ before... :P