我是C++新手,想做一个模板函数。我遇到了模板返回值的问题。代码是这样的
#include <iostream>
#include <cmath>
#include <gsl/gsl_rng.h>
#define pi 3.1415926535
using namespace std;
template <class T>
T cpradius(T a,T b,T p, int n)
{
const gsl_rng_type *R;
gsl_rng *r;
gsl_rng_env_setup();
R = gsl_rng_default;
r = gsl_rng_alloc(R);
T p1[n],p3[n],p2 ;
T radius[n] ;
for (int i = 0; i<n; i++)
{
p1[i] = gsl_rng_uniform(r);
p2 += p1[i];
}
for (int j = 0; j<n; j++)
{
p3[j] = p1[j]/p2;
radius[j] = sqrt(p3[j]*a*b*p/pi);
//cout << radius[j] << endl;
}
return radius[n];
}
int main(){
double r[30] = {0};
r[30] = cpradius(30.0,30.0,0.6,30);
for (int i = 0;i<30;i++){
cout << r[i] <<endl;
}
return 0;
}
然后,编译它:
g++ -Wall -I/usr/local/include/ tst3.cpp -lgsl -lgslcblas
结果是 1 列,30 个零:
0
0
0
...
0
似乎初始数组没有更新,有人帮助我吗?谢谢你!