[英]Array printing out garbage values
I have an excercise were I have to write a recursion function that calculates e^x using a formula.我有一个练习,我必须编写一个使用公式计算 e^x 的递归 function。 I managed to do that, but the exercise says that I have to store the results in an array, this is where I hit the wall, this is my code:
我设法做到了,但是练习说我必须将结果存储在一个数组中,这就是我碰壁的地方,这是我的代码:
double exp (double x, int n, int* fakt, double* xpot) {
static double result;
static int i;
static double *A;
A = (double *) malloc(n * sizeof(double));
if (i == n)
{
for(int k = 0; k < n; k++)
cout << A[k]; //this prints out garbage values
return result;
}
if (i != 0 || i != 1)
{
for (int j = 1; j <= i; j++)
*fakt = *fakt * j;
}
*xpot = pow(x, i);
result += *xpot / (double)*fakt;
A[i] = result;
*fakt = 1;
i++;
return exp(x, n, fakt, xpot);
} }
I would pass the array as the function argument, but the task specifically says that:我会将数组作为 function 参数传递,但任务明确指出:
double exp (double x, int n, int *fakt, double *xpot);
is the prototype.是原型。 My question is why the loop prints out garbage values, and is there a way to fix it?
我的问题是为什么循环打印出垃圾值,有没有办法解决它?
You do not initialize the values of A
thats why there is garbage printed.您没有初始化
A
的值,这就是打印垃圾的原因。
Also:还:
if (i != 0 || i != 1)
is equal to if (true)
. if (i != 0 || i != 1)
等于if (true)
。exp
function will leak a good amount of memory... A
is never free
dexp
function 都会泄漏大量 memory... A
永远不会free
dxpot
and fakt
might be nullptr
, what could go wrong? xpot
和fakt
可能是nullptr
, go 会出错吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.