2016-01-24 62 views
-2

該程序的目的是能夠輸入一組整數double值,並將其作爲總和輸出總距離。它也意味着識別最小和最大距離 - 以及計算兩個或更多距離的平均值。C++源代碼bug - 計算距離和總和的差異

我還希望能夠刪除我的程序中重複的代碼塊,我已經從字面上複製該代碼塊以獲得源代碼的第二部分工作。顯然有一種方法來刪除複製 - 但我不知道如何。

這裏的源:

/* These includes are all part of a custom header designed 
    by Bjarne Stroustrup as part of Programming: Principles and Practice 
    using c++ 
*/ 

#include<iostream> 
#include<iomanip> 
#include<fstream> 
#include<sstream> 
#include<cmath> 
#include<cstdlib> 
#include<string> 
#include<list> 
#include <forward_list> 
#include<vector> 
#include<unordered_map> 
#include<algorithm> 
#include <array> 
#include <regex> 
#include<random> 
#include<stdexcept> 

// I am also using the "stdafx.h" header. 

// reading a sequence of integer doubles into a vector. 
This could be the distance between two areas with different paths 

int main() 
{ 
vector<double> dist; // vector, double integer value 

double sum = 0;    // sum of two doubles 
double min = 0;    // min dist 
double max = 0;    // max dist 

cout << "Please enter a sequence of integer doubles (representing distances): \n"; 

double val = 0; 

while (cin >> val) 
{ 
    if (val <= 0) 
    { 
     if (dist.size() == 0) 
      error("no distances"); 

     cout << "The total distance is: " << sum << "\n"; 
     cout << "The smallest distance is: " << min << "\n"; 
     cout << "The greatest distance is: " << max << "\n"; 
     cout << "The average (mean) distance is: " << sum/dist.size() << "\n"; 

     keep_window_open(); 

     return 0; 
    } 

    dist.push_back(val); // stores vector value 

    // updating the runtime values 

    sum += val; 

    if (val > min) 
     min = val; 

    if (max < val) 
     max = val; 
} 
if (dist.size() == 0) 
    error("no distances"); 

cout << "The total distance is: " << sum << "\n"; 
cout << "The smallest distance is: " << min << "\n"; 
cout << "The greatest distance is: " << max << "\n"; 
cout << "The average (mean) distance is: " << sum/dist.size() << "\n"; 

keep_window_open(); 
} 

此外,我一直在試圖輸入源代碼中的小塊的東西,如「抓(runtime_error E)」的形式,但它預計某種形式的聲明我不知道如何讓它編譯沒有錯誤。

幫助刪除複製/重複的代碼塊來減少膨脹會很好 - 在其他所有方面。

+1

你究竟有什麼錯誤/具體問題? – Mat

+2

你的錯誤是什麼?不應該「這可能是兩個不同路徑的地區之間的距離」是一個評論?你也缺少'使用命名空間標準;'。 –

+0

我不錯過使用命名空間標準;因爲它是Bjarne Stroustrup自定義標題的一部分。我沒有任何特定的編譯錯誤(帶有錯誤檢查代碼) – Rudis

回答

0

而是具有whileif語句,你應該將二者結合起來的條件,以避免重複代碼:

while ((cin >> val) && (val > 0)) 

此外,您還需要初始化min的最大價值,而不是零,如果您希望第一次比較捕獲最小值的第一個可能值。

從重複代碼中製作函數是一種通用的解決方案,在您的情況下這不是一個好的選擇,原因有兩個:首先,它不是必需的,因爲它更容易並且更好地將控制流所以不需要在兩個地方調用該代碼。其次,在重複代碼中使用的局部變量太多,因此如果有重複代碼變成函數的原因,好的設計也會要求將某些或全部局部變量收集到一個對象中。

如果它不是更清潔並且更容易合併這兩個條件,那麼合併控制流程還是比創造兩個地方調用的函數更好。你感冒了:

if (val <= 0) 
{ 
    break; 
}