我正在尝试编写一个代码来解决将两个数字m和n作为用户输入然后按如下方式计算A(m,n)的问题:
1. A(m,n) = A(m,n-1) + A(m-1,n) , m,n >=0
2. A(m,n) = m-n if m<0 or n<0
Run Code Online (Sandbox Code Playgroud)
我在C中编写了以下代码,但问题是答案来得不正确,因为变量值的初始化为零,在递归过程中删除了值,我得到的答案是不正确的.有谁知道如何解决这个问题?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num1=0;
int num2=0;
int rows=0;
int columns=0;
int i,j,**array;
printf("Enter two non-negative integer numbers \n");
scanf("%d %d",&num1,&num2);
//create 2d-Array
rows=num1+1;
columns=num2+1;
array=malloc(rows * sizeof(int *));
for(i=0;i<rows;i++)
{
array[i]=malloc(columns*sizeof(int));
}
for (i = 0; i < rows; i++ )
{
for(j= 0; j < columns; j++ )
{
array[i][j]=0;
}
}
//Fill data in array
computeArray(array,rows,columns);
// Display contents of array
for (i = 0; i < rows; i++ )
{
for(j= 0; j < columns; j++ )
{
printf("array[%d][%d] = %d\n", i,j, array[i][j] );
}
}
getch();
return 0;
}
int computeArray (int **array, int rows, int columns)
{
int i,j;
for(i=0; i<rows;i++)
{
for(j=0;j<columns;j++)
{
array[i][j]=computeFunction(array,i,j);
}
}
return **array;
}
int computeFunction(int **array, int i, int j)
{
printf("Value reset by zero\n");
int value=0;
if((i<0)||(j <0))
{
value = i-j;
printf("Value contains i-j value\n");
return value;
}
else
{
value = (computeFunction(array,i,j-1)+ computeFunction(array,i-1,j));
printf("Value updated after else\n");
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
0,0的答案应为-2,但由于初始化问题,我得到0.如果您知道如何克服这个问题,请告诉我们?
它被正确计算 - 它应该是0.
- A(m,n)= A(m,n-1)+ A(m-1,n),m,n> = 0
- 如果m <0或n <0,则A(m,n)= mn
所以 A(0,0) = A(0,-1) + A(-1,0) = (0 - (-1)) + (-1 - 0) = 1 + (-1) = 0