获取错误消息“未在范围中声明”

时间:2014-04-14 17:11:11

标签: c++

我正在开发一个C ++项目,在编译时,我收到错误消息:

  

错误:此范围内未声明mean   错误:standard_dev未在此范围内声明

我的代码是

#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);
}

3 个答案:

答案 0 :(得分:0)

当你尝试使用它们时,还没有看到这些功能;编译器不知道它们是什么导致错误。要么在main()之前移动它们,要么将它们原型化,例如:

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

这将为编译器提供对这些符号的期望,因此当它在使用中看到它们时,它知道如何处理它们。

答案 1 :(得分:0)

任何名称必须在使用之前定义(相对于模板的例外情况很少)。您在声明

中使用名称mean
m =  mean(mydata, N);

但名称mean尚未定义。

在main

之前放置函数声明
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);
   //...

答案 2 :(得分:0)

您需要在文件顶部添加功能原型mean()std_dev()。否则,他们就不会存在。在主要功能。将整个函数复制到主函数上方的空间,或者为它们制作原型。祝你好运!