繁体   English   中英

阿克曼表生成

[英]Ackermann Table Geneation

我正在努力学习有关Ackermann函数,递归时间和函数学的更多信息,但是我的代码无法编译。 我感觉这与acktgen()的数组acktgen() ,但我不确定100%。

#include <stdlib.h>
#include <iostream>
using namespace std;

int ack(int m, int n){
    if(m==0) return n+1;
    else if (n==0) return ack(m,1);
    else return ack(m-1,ack(m,n-1));
}

int acktgen(const int s, const int t){
    int acktable[s+1][t+1];
    for (int i = 1 ; i= t+1; ++i){ //column labels
        acktable[0][i]= i-1 ;
    }
    for (int i = 1 ; i= s+1; ++i){  //row labels
        acktable[i][0]= i-1 ;
    } 
    for (int i = 1; i<=s+1; ++i){
        for (int j = 1; j<=t+1; ++j){
            acktable[i][j]= ack(i-1,j-1);
        }
    }
    return(acktable);
}

int main(){
    for(int i=0;i<5;i++) {
        for(int j=0;j<5;j++) {
            cout<<acktgen(4,4)[i][j]<< "\t";
        }
    }
}

我知道这不是最有效的Ackermann算法,但我仅以它为例。

编译器错误:

prog.cpp: In function 'int acktgen(int, int)':
prog.cpp:26:17: error: invalid conversion from 'int (*)[(t + 1)]' to 'int' [-fpermissive]
  return(acktable);
                 ^
prog.cpp:14:6: warning: address of local variable 'acktable' returned [-Wreturn-local-addr]
  int acktable[s+1][t+1];
      ^
prog.cpp: In function 'int main()':
prog.cpp:32:24: error: invalid types 'int[int]' for array subscript
    cout<<acktgen(4,4)[i][j]<< "\t";
                        ^

让我们来看一下每个错误和警告:

> prog.cpp: In function 'int acktgen(int, int)': prog.cpp:26:17: error:
> invalid conversion from 'int (*)[(t + 1)]' to 'int' [-fpermissive]  
> return(acktable);

您声明了acktgen函数以返回一个int,但是您返回的是地址。 我不知道您的意图是什么,但是如果要从数组中返回一个值,则返回该值,即

return acktgen[0][4];

或类似的东西。


> prog.cpp:14:6: warning: address of local variable 'acktable' returned
> [-Wreturn-local-addr]   int acktable[s+1][t+1];

您正在返回局部变量的地址。 这样做是C ++中未定义的行为,所以不要这样做。 函数返回时,所有局部变量都会消失。 因此,尝试返回(并使用)不存在的地址将不会起作用(或者它可能起作用,但只是偶然)。


> prog.cpp: In function 'int main()': prog.cpp:32:24: error: invalid
> types 'int[int]' for array subscript
>     cout<<acktgen(4,4)[i][j]<< "\t";

这是不正确的,因为acktgen返回一个int,而不是数组或类似数组的对象。

基本上,您需要向我们提供有关您期望在acktgen函数中返回的内容的更多信息。 真的应该是一个数组吗? 它应该只是一个值吗?


您的代码的一些注意事项:

1)在ANSI C ++中用非常数表达式声明数组是不合法的:

int acktable[s+1][t+1];

该行代码不是合法的C ++。 要模拟数组,可以使用std::vector<std::vector<int>>

std::vector<std::vector<int>> acktable(s+1, std::vector<int>(t+1));

2)您的循环条件写得不正确:

   for (int i = 1 ; i = t+1; ++i){ //column labels

看看中间条件-这就是您想要的,仅当i == t+1循环才继续吗? 之后,您会在循环中犯同样的错误。

其次,您的循环会越界访问数组。 C ++中的数组是基于0的,但是如果仔细观察一下循环,您会发现边缘数是1:

    for (int i = 1; i<=s+1; ++i){
        for (int j = 1; j<=t+1; ++j){
            acktable[i][j]= ack(i-1,j-1);
        }
    }

在最后一次迭代中会发生什么? 您访问acktable[s+1][t+1] ,这是超出范围的。 该数组的最高索引是st ,因为我们从0开始计数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM