以相反的顺序输出数组的元素

时间:2015-11-27 12:09:22

标签: c++ arrays reverse

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

我不确定自己是否走在正确的道路上,但我真诚地希望有人能建议我找到解决方案。 现在,我收到错误的“分段错误”'''' - 它可能与数组空间有关吗?

这是我目前的代码:

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;

}

2 个答案:

答案 0 :(得分:2)

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

无论如何,深入研究代码:似乎在计算count之后,变量a[i]的内容已被销毁...(a[i]==0退出{ {1}}循环)。

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

while

答案 1 :(得分:1)

由于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