为温度程序选择良好的值 我用C++学习了C++ 2个月:编程原理和实践。现在我在读关于错误的一章,在一节中作者谈到了逻辑错误。之前用一个程序作为例子,然后修改版本来理解错误。这是第一个节目: #include "std_lib_facilities.h" // find the highest, lowest and averega temperature int main() { vector<double> temps; for (double temp; cin >> temp;) temps.push_back(temp); double sum = 0; double high_temp = 0; double low_temp = 0; for (double x : temps) { if (x > high_temp) high_temp = x; if (x < low_temp) low_temp = x; sum += x; } cout << "Highest temperature : " << high_temp << '\n'; cout << "Lowest temperature : " << low_temp << '\n'; cout << "Average temperature : " << sum / temps.size() << '\n'; }

为温度程序选择良好的值 我用C++学习了C++ 2个月:编程原理和实践。现在我在读关于错误的一章,在一节中作者谈到了逻辑错误。之前用一个程序作为例子,然后修改版本来理解错误。这是第一个节目: #include "std_lib_facilities.h" // find the highest, lowest and averega temperature int main() { vector<double> temps; for (double temp; cin >> temp;) temps.push_back(temp); double sum = 0; double high_temp = 0; double low_temp = 0; for (double x : temps) { if (x > high_temp) high_temp = x; if (x < low_temp) low_temp = x; sum += x; } cout << "Highest temperature : " << high_temp << '\n'; cout << "Lowest temperature : " << low_temp << '\n'; cout << "Average temperature : " << sum / temps.size() << '\n'; },c++,vector,C++,Vector,如您所见,如果我输入,例如,一组与8月份相关的温度,我将得到错误的输出结果,因为我将只输入正值,但低温将保持0.0,除非数据中的一个温度在夏季不可能低于零 所以作者修改了这个程序: #include "std_lib_facilities.h" int main() { vector<double> temps; double high_temp = -1000; // initialize to impossibly low double low_temp = 100

如您所见,如果我输入,例如,一组与8月份相关的温度,我将得到错误的输出结果,因为我将只输入正值,但低温将保持0.0,除非数据中的一个温度在夏季不可能低于零

所以作者修改了这个程序:

#include "std_lib_facilities.h"

int main()
{

 vector<double> temps;

 double high_temp = -1000; // initialize to impossibly low 
 double low_temp = 1000; // initialize to impossibly high 
 double sum = 0; 
 int no_of_temps = 0; 

 for (double temp; cin >> temp;) {
 ++no_of_temps; 
sum += temp; 

if (temp > high_temp) high_temp = temp; 
if (temp < low_temp) low_temp = temp; 

 }

cout << "Highest temperature : " << high_temp << '\n';
cout << "Lowest temperature : " << low_temp << '\n';
cout << "Average temperature : " << sum / no_of_temps<< '\n';


}
我的问题在于作者要求我做的练习:

查一查。检查一些信息源,为我们程序的最小温度和最大温度常数选择合适的值。这些价值观将决定我们计划的有用性


这个练习的作者是什么意思?你认为这个计划还需要改进吗?最小温度和最大温度的值是多少?与编写此类程序所用的解决方案相关的问题有哪些?

您应该从这些常量开始,以便第一次比较总是成功的。选择+/-1000是可以的,但是当你不需要的时候,你就人为地限制了自己。更好的解决方案可能是选择绝对处于极端的常数:

double high_temp = -std::numeric_limits<double>::infinity();
double low_temp = std::numeric_limits<double>::infinity();

您输入的任何温度都将高于-inf,低于inf,这样比较就会成功,并做正确的事情。

我想问题应该是将最小温度和最大温度作为常量,因为低温和高温用于存储变量数据?编辑:虽然我不确定可以使用什么限制,因为它们会通过将温度限制在有效范围内而扭曲分析…嗯。。最高温度始终可以在0°K-273.15°C下初始化。使用值1000和-1000就是神奇常数的一个例子?如果是,为什么?