首页 > 解决方案 > 使用递归将整数值数组以相反的顺序输出到屏幕

问题描述

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++arraysrecursion

解决方案


我测试了你的程序..

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

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


推荐阅读