积累错误

sta*_*ust 0 c++ iteration accumulate

我有一个很直截了当的问题.以下代码打印出摄氏度和华氏度.我的问题是它迭代的次数.对于较小的数字,例如从0开始,在10处停止,步长为1.1.循环完成后,它将打印出正确的迭代次数.

但对于大数字0-11000000,步骤1.1将打印出错误的迭代次数.为什么会这样?由于1100000/1.1应该在1000001左右,但我得到990293.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

   float start, stop, step;
   int count = 0;

   cout << "start temperature: ";
   cin >> start;
   cout << "stop temperature: ";
   cin >> stop;
   cout << "step temperature: ";
   cin >> step;

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

   while(start <= stop)
   {
      count++;
      float c, f;
      c = (5.0/9)*(start-32);
      f = 32+(9.0/5)*start;
      cout << setw(10) << fixed << setprecision(2) << c << setw(15) << start << setw(15) << fixed << setprecision(2) << f  << " count: " << count << endl;

      start = start + step;
   }
   cout << "The program loop made " << count << " iterations." << endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 5

浮点舍入错误.从本质上讲,浮点数不是100%准确的表示,每次计算都会出现错误,并且当您反复添加它们时,您将添加越来越多的错误.你应该做的是计算一次步数,将其存储在一个整数中,然后循环多次.