我正在處理一個問題,這與c + +中的動態分配有關。我有以下函數來計算一個信號功能不返回什麼suppossed返回-C++
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!\n\n");
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;
}
奇怪的是,在執行程序時,我得到從與邏輯均方根的功能的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!\n\n");
//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;
}
如果您正在調用函數並將函數的結果分配給其他函數,則返回值僅起作用。如果你只是想讓它打印一些'void'就沒有問題。 –
*「首先,如果我理解正確,double *表示參數需要動態定義。」*不,它只表示參數是指針。它沒有說明它指向什麼。但是你可能應該返回mean和rms,而不是從指針設置一些變量。 – juanchopanza
@EliSadoff感謝您的評論!事實上,我不想只打印輸出。我想使用輸出進行後續計算! – Thanos