程序打印数组中的所有数字,向后打印

Program prints all digits from array, prints backwards

本文关键字:打印 数字 数组 程序      更新时间:2023-10-16

我正在制作一个程序,打印数组中的所有数字(以整数形式输入),它可以工作,但数字是向后打印的,我不知道如何反转它们。有人能帮忙吗?

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

void explode(int number,int array[])
{
   while (number > 0) {
      int digit = number % 10;
      cout << digit << 'n';
      number /= 10;
   }
}

int main()
{
   int digits[100];
   int numdigits;
   int n;
   cout << "Enter number: ";
   cin >> n;
   //  numdigits = explode(n,digits);
   cout << "[";
   while (n > 0) {
      int digit = n % 10;
      n /= 10;
      digits[digit] = digit;
      cout << digits[digit];
   }
   cout << "]" << endl;
}

您只需要使用reverse()<algorithm>反转数组。

代码:

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
using namespace std;
int array_c = 0;
void explode(int number,int array[])
{
   while (number > 0) {
      int digit = number % 10;
      number /= 10;
      array[array_c++] = digit;
   }
}

int main()
{
   int digits[100];
   int numdigits;
   int n;
   cout << "Enter number: ";
   cin >> n;
   explode(n,digits);
   reverse(digits,digits+array_c);
   cout << "[";
   for(int i = 0; i < array_c; ++i)
        cout<<digits[i];
   cout << "]" << endl;
}

的使用

digits[digit] = digit;

是不对的。你可能打算使用

digits[numdigits] = digit;

你可以把工作分成两步来解决你的问题。在第一步中,存储数字。在第二步中,打印数字。

int numdigits = 0;
while (n > 0) {
   cout << "n: " << n << endl;
   int digit = n % 10;
   n /= 10;
   digits[numdigits++] = digit;
}
// Make sure to print them in reverse order.
cout << "[";
for ( ; numdigits > 0; )
{
   cout << digits[--numdigits];
}
cout << "]" << endl;