Aug 14, 2010 at 4:47pm UTC
the following is the code...
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float start_temp,stop_temp;
float step,F,C;
cout<<"start temperature:";
cin>>start_temp;
cout<<"stop temperature:";
cin>>stop_temp;
cout<<"step temperature:";
cin>>step;
float i=0;
cout<<setw(10)<<"celsius"<<setw(15)<<"fahrenheit"<<endl;
cout<<setw(25)<<"celsius"<<setw(15)<<"fahrenheit"<<endl;
for(i=start_temp;i<=stop_temp;i=i+step)
{
C=(5.0/9.0)*(i-32);
F=32+(9.0/5.0)*i;
cout<<setprecision(2);
cout.setf(ios::fixed);
cout<<setw(10)<<C<<setw(10)<<i<<setw(10)<<F<<endl;
}
}
and the output for the above code is:
start temperature: 0
stop temperature: 11
step temperature: 1.1
-17.78 0.00 32.00
-17.17 1.10 33.98
-16.56 2.20 35.96
-15.94 3.30 37.94
-15.33 4.40 39.92
-14.72 5.50 41.90
-14.11 6.60 43.88
-13.50 7.70 45.86
-12.89 8.80 47.84
-12.28 9.90 49.82
-11.67 11.00 51.80
but i am not able to print the last line of output.i.e.,-11.67 11.00 51.80
i dont know why it is not printing the last line of output..
but it is working for the following output:
start temperature: 60
stop temperature: 80
step temperature: 2
15.56 60.00 140.00
16.67 62.00 143.60
17.78 64.00 147.20
18.89 66.00 150.80
20.00 68.00 154.40
21.11 70.00 158.00
22.22 72.00 161.60
23.33 74.00 165.20
24.44 76.00 168.80
25.56 78.00 172.40
26.67 80.00 176.00
Aug 14, 2010 at 5:22pm UTC
It's because floating point numbers tend not to be completely accurate, the variable i , is actually 11.000001 when the loop tests for the condition, which means it fails since it's more than 11.
Using doubles, rather than floats fixes it (as i is actually 10.9999999999999998)
Or you can just add a small number to:
for (i=start_temp;i<=stop_temp + NUMBERHERE ;i=i+step)
like say 0.00001, which will account for any innaccuracies due to using floating point numbers.
Edit - I'd go for the second option btw, as even using a double, you will probably still get errors when using different numbers
Oh, and there may be a better way to do it, but I'm just learning c++ atm ;)
Last edited on Aug 14, 2010 at 5:29pm UTC
Aug 14, 2010 at 6:18pm UTC
Comparing floating point numbers for equivalence is dangerous because of tiny inaccuracies. For that reason you should avoid doing a <= in your loop.
It is better to look at the range of values you want to iterate over and always compare less-than (<).