2014-04-14 162 views
0

我在C++項目工作「不在範圍內聲明」,並在編譯時,我收到錯誤消息:收到錯誤消息

error: mean was not declared in this scope
error: standard_dev was not declared in this scope

我的代碼是

#include <iostream> 
#include <iomanip> 
#include <fstream> 
#include <cmath> 
#include <string> 

using namespace std; 

int main() 
{ 
    int N(0); 
    char filename[100]; 
    double m, stdev; 
    string temp; 

    double next; 
    int count = 0; 
    cout << "Enter name of file: "; 
    cin >> filename; 

    ifstream myfile; 
    myfile.open(filename); 
    while (myfile >> next) 
    { 
     count++; 
    } 
    N = count; 
    double* mydata; 
    mydata = new double[N]; 

    for (int i = 0; i < N; i++) 
    { 
     myfile >> mydata[i]; 
    } 
    m = mean(mydata, N); 
    stdev = standard_dev(mydata, m, N); 
    cout << "The standard deviation is:" << stdev << endl; 

    myfile.close(); 
    delete[] mydata; 
    return 0; 
} 

double mean(double* mydata, double N) 
{ 
    double sum(0), m; 
    for (int i = 0; i < N; i++) 
    { 
     sum += mydata[i]; 
    } 
    m = (sum/(double) N); 
    return (m); 
} 
double standard_dev(double* mydata, double m, int N) 
{ 
    double* mydata2 = new double[N]; 
    for (int i = 0; i < N; i++) 
    { 
     mydata2[i] = pow((mydata[i] - m), 2); 
    } 
    double sum(0), S, X; 
    for (int i = 0; i < N; i++) 
    { 
     sum += mydata2[i]; 
    } 
    X = sum/N; 
    S = sqrt(X); 
    return (S); 
} 

回答

0

這些功能有當你嘗試使用它們時還沒有看到;編譯器不知道它們是什麼導致了錯誤。無論是main()之前移動它們或它們的原型,比如:

double mean(double * mydata, double N); 
double standard_dev(double * mydata, double m, int N); 
int main() 
{ 
    ... 

這將使編譯它那些符號的期望,所以當它看到他們在使用它知道如何與他們無關。

0

任何名稱必須在其使用之前定義(極少數例外情況相對於模板)。您在聲明

m = mean(mydata, N); 

使用名稱mean但名稱mean尚未確定。之前主要

double mean(double *mydata, double N); 
double standard_dev(double *mydata, double m, int N); 

int main() 
{ 
//... 

或者其使用前

將函數聲明。

int main() 
{ 
    double mean(double *mydata, double N); 
    double standard_dev(double *mydata, double m, int N); 

    //... 
    m = mean(mydata, N); 
    //... 
0

你需要有原型的功能mean()std_dev()在你的文件的頂部。否則,它們在主函數中不存在。將整個功能複製到主功能上方的空間,或者爲它們製作原型。祝你好運!