我怎么能写这个算法的基础案例?

时间:2012-08-31 04:31:58

标签: c arrays recursion

我遇到了算法问题:我需要做的是通过递归来乘以数组的元素。这是我到目前为止所得到的:

 #include <stdio.h>
    void vector(int vec[],int tam) {
    // gets a simple array
        int i;
        for (i=0; i<tam; i++) {
            printf("Ingrese un numero: ");
            scanf("%d",&vec[i]);
        }
    }
    int mv(int vec[], int tam, int pos) {
     // need help with the base and general case!
        if (tam==0) {
            return 1;
        } else {
            return vec[pos]*mv(vec,tam,pos+1);
        }   
    }

    int main() {
        int vec[3];
        vector(vec,3);
        printf("%d",mv(vec,3,0));
    }

1 个答案:

答案 0 :(得分:0)

基本情况为if (pos == tam) return 1;

您还必须确保数组不为空