函数不会返回返回c 的内容
Function does not return what is suppossed to return- c++
我正在处理一个问题,这与C 中的动态分配有关。我有以下功能来计算信号的RM
的RMSvoid 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
。阵列中的所有其他值都是非初始化的,这意味着它们的值将是不确定的(并且似乎是随机的)。读取那些非专业化值将导致不确定的行为。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数