函数不会返回返回c 的内容

Function does not return what is suppossed to return- c++

本文关键字:返回 函数      更新时间:2023-10-16

我正在处理一个问题,这与C 中的动态分配有关。我有以下功能来计算信号的RM

的RMS
void FindRMS(int points, double* signal_x, double* signal_y, int presamples, double* mean, double* rms)
{       
    //double fraction_presamples_RMS = 0.9; // fraction of presamples to calculate RMS
  //Safety condition
  if (presamples>points) {
    printf("nERROR: Too many presamples!nn");
    return;
  }
  //Main procedure
  (*rms)  =0.;  
  (*mean) =0.;
  for (int i=0; i<presamples; i++) {
    (*mean)+=signal_y[i];
    (*rms)+=pow(signal_y[i],2);
  }
  (*mean)/=presamples;
  (*rms)=sqrt((*rms)/presamples-pow((*mean),2));
    cout << "RMS was found to be : " << (*rms) << endl;
}

首先,如果我正确理解,double* <var>意味着该参数将被动态定义,这意味着其大小将受到硬件的限制。

我要做的就是在我的代码中调用此功能。示例代码为以下

void Analyze(unsigned int first_run, unsigned int last_run, unsigned int last-segment){
    int points = 9e6;//hSignal->GetNbinsX();
//double x[points], y[points], derivative[points]; // SIZE limited by COMPILER to the size of the stack frame
    double* x          = new double[points];           // SIZE limited only by OS/Hardware
    double* y          = new double[points];
    double* derivative = new double[points];
    double* mean       = new double[points];
    double* rms        = new double[points];
    for (int i = 0; i < points; i++){
        x[i] = hSignal->GetBinLowEdge(i+1);
        y[i] = hSignal->GetBinContent(i+1);
        //cout << " Bin Center " << hSignal->GetBinLowEdge(2) << endl;
    }
    FindRMS(points, x, y, 0.9*points, mean, rms);
    delete[] x;
    delete[] y;
    delete[] mean;
    cout << "The value of rms[10] = " << rms[10] << endl;
}

很奇怪的是,执行程序时,我会从逻辑RMS上从功能中获得一个cout,而在程序结束之前,我得到RMS为0。

关于为什么会发生的任何想法或建议?问题是我必须按原样坚持该功能,因为它属于我必须坚持...

的库

我想将功能更改为返回double*而不是void,但实际上没有任何改变...这是修改的函数

double* FindRMS(int points, double* signal_x, double* signal_y, int presamples, double* mean, double* rms)
{       
    //double fraction_presamples_RMS = 0.9; // fraction of presamples to calculate RMS
  //Safety condition
  if (presamples>points) {
    printf("nERROR: Too many presamples!nn");
    //return;
  }
  //Main procedure
  (*rms)  =0.;  
  (*mean) =0.;
  for (int i=0; i<presamples; i++) {
    (*mean)+=signal_y[i];
    (*rms)+=pow(signal_y[i],2);
  }
  (*mean)/=presamples;
  (*rms)=sqrt((*rms)/presamples-pow((*mean),2));
    cout << "RMS was found to be : " << (*rms) << endl;
    return rms;
}

在功能FindRMS中,您仅设置与rms[0]相同的*rms。阵列中的所有其他值都是非初始化的,这意味着它们的值将是不确定的(并且似乎是随机的)。读取那些非专业化值将导致不确定的行为