2015-01-31 20 views
1

我正在使用本書學習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什麼值?用於編寫此類程序的解決方案有哪些相關問題?

+0

我想問題應該是'min_temp'和'max_temp'作爲常量,因爲'low_temp'和'high_temp'用於存儲變量數據?編輯:雖然我不確定可以使用什麼限制,因爲他們會通過將「temp」鉗位到有效範圍來扭曲分析... – Sam 2015-01-31 19:04:24

+0

嗯..最高溫度始終可以在0°K(-273.15 °C) – 2015-01-31 19:14:18

回答

0

你應該從這樣的常量開始,這樣第一次比較總是會成功的。選擇+/- 1000是可以的,但是當你不需要的時候,你可以人爲地限制自己。一個更好的解決方案可能是選擇那些肯定是在極端的常數:

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

輸入會比-inf高,比inf下,這樣比較會成功,做正確的事的任何溫度。

+0

使用值1000和-1000是「魔術常量」的一個例子?如果是這樣,爲什麼? – 2015-02-01 16:25:16