逆序输出数组元素

Output the elements of an array in reverse order

用户将未知数量的整数放入数组中(动态)。程序必须以相反的顺序输出这些数字,例如: 整数倒序排列。 例子。 324,12,5987 --> 423, 21, 7895 例子。 123, 100 --> 321, 1(删除两个 0)

我不确定我是否走在正确的道路上,但我真诚地希望有人能给我建议一个解决方案。 现在,我收到“'Segmentation fault'”的错误 - 它可能与数组 space 相关吗?

这是我目前的代码:

int main()
{

    int n,sk,rez;


    int *a;


    cout << "How many integers will there be? : " << endl;
    cin >> sk;

    a = new int[sk];


    for (int i = 0; i < sk; i++)
    {

        cout << "Write an integer: " << endl;
        cin >> n;
        a[i] = n;
    }


    for (int i = 0; i < sk; i++)
    {
        // Gets amount of the digits of every integer.

        int count, new_num = 0;
        int* skaits;

        while(a[i] > 0)
        {
        count++;
        a[i] = a[i]/10;
        }
        skaits = new int [count];
        for (int j = 0; j<count; j++)
            {
                skaits[j] = count; //  Exmp. I write 324,12 , loop calculates 3 and 2 and puts that amount in an array.

                // Loop to output integers in reverse order. Exmp. 324,12,5987 --> 423, 21, 7895

                for (int k = 0; k<skaits[j]; k++)
                {
                    new_num = new_num * 10 + (a[k] % 10);
                    a[k] = a[k]/10;


                }
                cout << new_num << endl;
            }

    }



    delete []a;
    return 0;

}

作为一般规则:尝试使您的代码更加模块化。我希望找到一个函数来计算单个数字的倒数。这更容易编写,也更容易调试,因为您将两个任务分开:收集数据、反转整数。

无论如何,深入查看您的代码:似乎在您计算 count 之后,变量 a[i] 的内容已被破坏...(a[i]==0 退出while 循环)。

反转十进制数的简单方法:

int reverse(int n) {
    int m=0;
    while (n>0) {
        m *= 10;
        m += n%10;
        n /= 10;
    }
    return m;
}

此处 segmentation fault 出现是因为 count 未初始化。 我在你的程序中发现了很多错误,例如:

 int count, new_num = 0;// here count is not initialized also need count=0;
        int* skaits;

        while(a[i] > 0)
        {
        count++; // without initialize how you increase count 
        a[i] = a[i]/10;
        }// after this your number in a[i] is become 0. so what will you find

      skaits = new int [count];// no need extra skaits. you have count already

最好用一个函数来反转a[i]的每个数字。

long reverse(long n) {
   static long r = 0;

   if (n == 0) 
      return 0;

   r = r * 10;
   r = r + n % 10;
   reverse(n/10);
   return r;
} 

您可以按如下方式操作:

for(int i=0;i<sk;i++)
 {
  int new_num=reverse(a[i);
   a[i]=new_num;
   cout<<a[i]<<endl;
}

或者你也可以像下面这样:

for (int i = 0; i < sk; i++)
    {

        cout << "Write an integer: " << endl;
        cin >> n;
        a[i] = n;
    }
    for (int i = 0; i < sk; i++)
    {
        // Gets amount of the digits of every integer.
        int reverse=0;
        while (a[i] != 0)
        {
            reverse = reverse * 10;
            reverse = reverse + a[i]%10;
            a[i]= a[i]/10;
        }
        cout<<reverse<<endl;

    }

另一种方法,首先让每个数字先 int to string 然后 reverse 它。