使用递归以相反的顺序将整数数组输出到屏幕

问题描述 投票:0回答:1
void IntegerReversed(int* a, int n)
{
    if (n < 1) {
        return;
    }
    else {
        cout << a[n - 1] << endl;
        Integer(a, n - 1);
    }
}

int main()
{
    int* a;
    int n;
    cout << "Input n: ";
    cin >> n;
    a = new int[n];
    for (int i = 0;i < n;i++) {
        cin >> *(a + i);
    }
    cout << "Integer values reversed in array: " << endl;
    IntegerReversed(a, n);
}

嗨,我的代码使用递归以相反的顺序将整数值数组输出到屏幕。

但是它只打印第一个正确的元素

输入:a [4] = {1,2,3,4}

但是输出:4,1,2,3

我要打印:4,3,2,1您能帮我解决此代码吗

c++ arrays recursion
1个回答
0
投票

我测试了您的程序。

void IntegerReversed(int* a, int n)
{
    if (n < 1) {
        return;
    }
    else {
        cout << a[n - 1] << endl;
        IntegerReversed(a, n - 1);
    }
}

而这只是一个拼写错误。在递归调用中..

© www.soinside.com 2019 - 2024. All rights reserved.