Hello All, I was working on an exercise provided in this lesson:
https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-variables/exercises/review
and I tried to make a Fahrenheit to Celsius converter. My code is as follows:
#include <iostream>
int main() {
std::cout << "Temperature Converter \n \n";
std::cout << "Temperature in Farenheit: ";
int tempf = 0;
std::cin >> tempf;
std::cout << "\n";
double tempc = (tempf - 32) * (5 / 9);
std::cout << "The temperature in Celcius is: " << tempc << " \n";
}
I would put in a temperature in Fahrenheit and it would always give me 0 when it returned the Celsius value. I figured out that it was a problem with the parenthesis around the 5/9, but I don’t know why. Does division work in a weird way in C++?
Thanks!
See Issue #1 in the following post regarding integer division:
https://discuss.codecademy.com/t/c-calculator-temperature-conversion-formulas-not-working/744313/2
std::cout << 5 / 9 << "\n";
// 0
std::cout << 5.0 / 9 << "\n";
// 0.555556
Also, if you want to restrict user to only enter integer values for Fahrenheit, then int tempf = 0;
works.
But, if you want to allow the user to enter decimal values, then your declaration should be double tempf;
1 Like