C++ program converts fahrenheit to celsius
(5/9)
will by default be computed as an integer division and will be zero. Try (5.0/9)
Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9
In C++, 5/9 computes the result as an integer as both the operands are integers. You need to give an hint to the compiler that you want the result as a float/double. You can do it by explictly casting one of the operands like ((double)5)/9;
EDIT
Since it is tagged C++, you can do the casting bit more elegantly using the static_cast
. For example: static_cast<double>(5)/9
. Although in this particular case you can directly use 5.0/9 to get the desired result, the casting will be helpful when you have variables instead of constant values such as 5.
In your code sample you are trying to divide an integer with another integer. This is the cause of all your trouble. Here is an article that might find interesting on that subject.
With the notion of integer division you can see right away that this is not what you want in your formula. Instead, you need to use some floating point literals.
I am a rather confused by the title of this thread and your code sample. Do you want to convert Celsius degrees to Fahrenheit or do the opposite?
I will base my code sample on your own code sample until you give more details on what you want.
Here is an example of what you can do :
#include <iostream>
//no need to use the whole std namespace... use what you need :)
using std::cout;
using std::cin;
using std::endl;
int main()
{
//Variables
float celsius, //represents the temperature in Celsius degrees
fahrenheit; //represents the converted temperature in Fahrenheit degrees
//Ask for the temperature in Celsius degrees
cout << "Enter Celsius temperature: ";
cin >> celsius;
//Formula to convert degrees in Celsius to Fahrenheit degrees
//Important note: floating point literals need to have the '.0'!
fahrenheit = celsius * 9.0/5.0 + 32.0;
//Print the converted temperature to the console
cout << "Fahrenheit = " << fahrenheit << endl;
}
Best way would be
#include <iostream>
using namespace std;
int main() {
float celsius;
float fahrenheit;
cout << "Enter Celsius temperature: ";
cin >> celsius;
fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
}
:)