我的程序到目前爲止,我的問題是我必須包括每個cout/cin代碼之後的if語句還是有一種方法來推廣它? :if語句爲C++
#include <iostream>
using namespace std;
int main()
{
double watts, hours_per_day, watt_hours, dollars_per_wh, result;
dollars_per_wh= .00008;
cout << " How many Watts for the Air conditioner? ";
cin >> watts;
cout << " How many hours/day do you run the Air Conditioner? ";
cin >> hours_per_day;
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return 1;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return 1;
}
cout << "How many Watts for the Television? " ;
cin >> watts;
cout << "How many hours/day do you run the Television? " ;
cin >> hours_per_day;
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return 1;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return 1;
}
cout << "How many Watts for the Washer? " ;
cin >> watts;
cout << "How many hours/day do you run the Washer? " ;
cin >> hours_per_day;
if (watts< 0)
{
cout << "Error- negative watts detected " << endl;
return 1;
}
if (hours_per_day< 0)
{
cout << "Error - negative hours/day detected " << endl;
return 1;
}
return 0 ;
}
您錯過了最重要的檢查:您沒有對輸入進行任何驗證以確保輸入實際成功。例如,嘗試輸入「abcdef」時詢問瓦數。你必須在任何輸入操作(例如`if(!(cin >> watts)){/ * handle error * /}`或類似的東西)之後檢查流的狀態。至於所有這一切的概括,當然你可以將這些驗證塊重構爲一個單獨的函數;對於每個塊,將共同的東西移動到一個新的函數中,並傳遞那些不常見的東西作爲參數。 – 2011-01-19 06:45:59
「......有沒有辦法將其推廣?」是的,這正是功能的主要目的之一。以下已經有幾個例子,所以我不會再添加其他例子。但是這看起來像是一個很好的項目,可以學習如何編寫可應用於每個AC,TV和洗衣機箱的功能。 – 2011-01-19 07:36:40