tags:

views:

12

answers:

0

Hello, I got another question which continues from this one

http://stackoverflow.com/questions/3695178/accumulation-error

I heard some good idea and tried to implement it to the program. That is that I could store the results in Integer type first and afterward convert it to a float type.

But the problem is that I can produce the correct value by hard typing which next value I want. For example this one:

cout << setprecision(2) << fixed << (1100000 - 11) / 10.0f << endl;

will give me the correct value, but the same calculation I do in a loop it will still give me the wrong answer. How come? I store it in a int first and calculate a float type when I output it to the stream.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

   int start=0, stop=11000000, step=11;

   int count = 0;  

   cout << setw(10) << "celsius" << setw(15) << "fahrenheit" << endl;
   cout << setw(25) << "celsius" << setw(15) << "fahrenheit" << endl;

   while((start + step * count) <= stop)
   {
      int temp = (start + step*count);

      float c = (5.0 / 9.0) * (temp - 32.0);
      float f = 32.0 + (9.0 / 5.0) * temp;

      if(count < 5 || count > 999995)
      {
         cout << setw(10) << fixed << setprecision(2) << c/10.0f
              << setw(15) << temp / 10.0f
              << setw(15) << fixed << setprecision(2) << f / 10.0f << endl;
      }
      else if(count == 5)
      {
         cout << setw(10) << "..."
              << setw(15) << "..."
              << setw(15) << "..." << endl;     
      }
      count++;
   }

   cout << "The program loop made " << count << " iterations." << endl; 
   return 0;
}