c - 如何在以下代码中的每个函数调用中阻止该值变为零?

标签 c logic

我正在尝试编写代码来解决将两个数字 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

我用 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;
    }
}

0,0 的答案应该是 -2,但由于初始化问题,我得到的是 0。如果您知道如何解决这个问题,请告诉我?

最佳答案

计算正确 - 它应该为 0。

  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

所以 A(0,0) = A(0,-1) + A(-1,0) = (0 - (-1)) + (-1 - 0) = 1 + (- 1) = 0

关于c - 如何在以下代码中的每个函数调用中阻止该值变为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24541771/

相关文章:

c - 读一个C文件,多读一行,为什么?

c++ - 如何在openCL中将图像从全局内存复制到本地内存

logic - 什么是处理规则验证的最佳方法

math - 希尔伯特系统-自动打样

c - 哈希表搜索和移动过去已删除的项目

javascript - 如果我们处于默认状态并且没有选择其他选项,则不执行任何操作。如果从其他选项回到默认状态,请执行某些操作

c - 不使用数组来反转数字的程序

c - 如何将 2d 数组中的 1 个字符转换为 1d 数组

c - 如何规避 GCC 中的格式截断警告?

c - 作为迭代函数非递归运行 picoC