2015-05-19 189 views
-4

我正在開發一個程序,但我面臨一些問題。以下程序從數字文件計算平均值,最大值等。但是我無法在下面的代碼中計算標準偏差。 編譯器是MS視覺工作室10標準偏差問題

int main() 
{ 
    ifstream infile; 
    float num; 
    float total; 
    float x; 
    float aver; 
    float sumDiffSqr; 
    float stdDev; 
    vector<std::string> files = { "mynumberlist1.txt" }; 

    for (int i = 0; i<files.size(); i++) 
    { 
     x = 0; 
     total = 0; 
     infile.open(files.at(i)); 
     if (!infile.is_open()) 
     { 
      cout << "Error opening file\n"; 
      return 1; 
     } 
     while (!infile.eof()) 
     { 
      infile >> num; 
      total = total + num; 
      x++; 
     } 

     aver = (total - num)/(x - 1); 

     cout << "The last number in this range is: " << num << "\n"; 
     cout << "The sum of this range is: " << (total - num) << '\n'; 
     cout << "The number of items in this range is: " << x - 1 << '\n'; 
     cout << "The average of this range is: " << aver << '\n'; 
     cout << "" << '\n'; 
     cout << "Press enter to continue..." << '\n'; 

     sumDiffSqr = 0; 

     for (i = 0; i < num; i++) 
     { 
      sumDiffSqr = sumDiffSqr + pow((num[i] - aver), 2); 
     } 

     stdDev = sqrt(sumDiffSqr/num); 

     infile.close(); 
     getchar(); 
    } 

    return 0; 
} 
+2

這是否甚至編譯? – mathematician1975

+2

爲什麼你不能計算標準偏差?是因爲你不知道那是什麼嗎? – rghome

+0

您正在錯誤地檢查您的輸入循環,請參閱[爲什麼eof不好](http://stackoverflow.com/questions/5837639/eof-bad-practice)。 –

回答

1

樣子你會需要你的號碼保存到一個載體,至少在標準偏差:

std::vector<double> numbers; 
double value; 
double sum = 0.0; 
while (infile >> value) 
{ 
    numbers.push_back(value); 
    sum += value; 
} 

const double average = sum/(double)numbers.size(); 
double sumDiffSqr = 0.0; 
std::vector<double>::const_iter iter; 
for (iter = numbers.begin(); 
    iter != numbers.end(); 
    ++iter) 
{ 
    const double temp_value = *iter - average; 
    sumDiffSqr += temp_value * temp_value; 
} 
+0

'value'沒有類型。還要考慮for..in循環而不是詳細的迭代器。 – Gerard

+0

@傑拉德,謝謝你的好意。我做了更正。 –