該程序的目的是能夠輸入一組整數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)」的形式,但它預計某種形式的聲明我不知道如何讓它編譯沒有錯誤。
幫助刪除複製/重複的代碼塊來減少膨脹會很好 - 在其他所有方面。
你究竟有什麼錯誤/具體問題? – Mat
你的錯誤是什麼?不應該「這可能是兩個不同路徑的地區之間的距離」是一個評論?你也缺少'使用命名空間標準;'。 –
我不錯過使用命名空間標準;因爲它是Bjarne Stroustrup自定義標題的一部分。我沒有任何特定的編譯錯誤(帶有錯誤檢查代碼) – Rudis