Loop problem

The program should create two integer variables for the temperature in Celsius and Fahrenheit. Initialize the temperature to 100 degrees Celsius. In a loop, decrement the Celsius value and compute the corresponding temperature in Fahrenheit until the values are the same.
But for some reason i either get no output or an out put of -43.

#include <iostream>
using namespace std;

int main()
{
int celsius;
int fahrenheit;

fahrenheit = 0;
celsius = 100;

while(celsius != fahrenheit)
{
fahrenheit = ((9 * celsius) / 5) + 32;
celsius--;
}

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

cout << celsius << endl;
cout << fahrenheit;



return 0;

}
with a bit math you will see that the value is -40.

your problem is that you use int for celsius and fahrenheit, instead you need to use double due to the precision.

the precision (or better the lack thereof) also makes a direct comparison (like celsius != fahrenheit) problematic. Better subtract both values and compare the absolute result against a very small value (like 0.00001 or so)

See
http://cplusplus.com/reference/cmath/fabs/
Topic archived. No new replies allowed.