我有一个非常直截了当的问题。以下代码打印出摄氏度和华氏度。 我的问题是它迭代的次数。对于少数例如开始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;
}
答案 0 :(得分:5)
浮点舍入错误。从本质上讲,浮点数不是100%准确的表示,每次计算都会出现错误,并且当您反复添加它们时,您将添加越来越多的错误。你应该做的是计算一次步数,将它存储在一个整数中,然后循环多次。
答案 1 :(得分: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;
}
这种循环风格的主要好处是每次迭代(除输出外)与顺序无关,因此可以展开并(理论上)并行化。