0

非常に率直な質問があります。次のコードは、摂氏と華氏を出力します。私の質問は、それが繰り返される回数についてです。少数の場合、たとえば0を開始し、1.1のステップで10で停止します。ループが終了すると、実行した正しい反復回数が出力されます。

ただし、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;
}
4

2 に答える 2

5

浮動小数点の丸め誤差。基本的に、浮動小数点数は100%正確な表現ではなく、実行するすべての計算にエラーがあり、繰り返し追加すると、ますます多くのエラーが追加されます。あなたがすべきことは、ステップ数を一度計算し、それを整数に格納してから、それを何度もループすることです。

于 2010-09-12T14:32:27.440 に答える
0

記録として、クリーンアップされたバージョンは次のようになります。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

   double start, stop, step;

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

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

   unsigned steps = (stop - start) / step;

   for(unsigned i = 0; i < steps; ++i)
   {
      double temp = start + i * step;
      double c = (5.0 / 9.0) * (temp - 32.0);
      double f = 32.0 + (9.0 / 5.0) * temp;
      // This is a real good example of why people hate <iostream> formatting.
      // If you want formatting that's quite different from the default, it
      // gets too verbose too fast. Using C stdio: 
      //printf("%10.2f%15.2f\n", c, f);
      cout << setw(10) << fixed << setprecision(2) << c
           << setw(15) << fixed << setprecision(2) << f << endl;
   }

   cout << "The program loop made " << steps << " iterations." << endl;

   return 0;
}

このスタイルのループの主な利点は、各反復が(出力を除いて)順序に依存しないため、展開して(理論的に)並列化できることです。

于 2010-09-12T15:12:04.273 に答える