我正在使用本書學習C++ 2個月:編程原理和使用C++的實踐。現在我正在閱讀有關錯誤的章節,並在一節中提到了邏輯錯誤。以程序爲例,然後修改版本以瞭解錯誤。這是第一個節目:爲溫度程序提供良好的值
#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';
}
正如你可以看到,如果我進入,例如,一組有關八月份溫度的,我會得到錯誤的輸出中的結果,因爲我只輸入正值,但LOW_TEMP會除非數據中的一個溫度低於零(夏天不可能),否則保持爲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';
}
我的問題在於鍛鍊,作者問我做:
關注一下吧。檢查一些信息來源,爲我們的程序的min_temp(「最低溫度」)和max_temp(「最高溫度」)常量選擇合適的值。這些價值觀將決定我們計劃的實用性。
這個練習的作者是什麼意思?該計劃在你看來還需要一些改進?你會給min_temp和max_temp什麼值?用於編寫此類程序的解決方案有哪些相關問題?
我想問題應該是'min_temp'和'max_temp'作爲常量,因爲'low_temp'和'high_temp'用於存儲變量數據?編輯:雖然我不確定可以使用什麼限制,因爲他們會通過將「temp」鉗位到有效範圍來扭曲分析... – Sam 2015-01-31 19:04:24
嗯..最高溫度始終可以在0°K(-273.15 °C) – 2015-01-31 19:14:18